Break a long string into multiple lines

Let's imagine that we have this String as an input:
TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=

And we want to split that large string into lines, and the lines shouldn't contain more than a certain number of characters in each.

So here is the Java code:

import java.util.Scanner;
public class WrapText {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Input:\n");
String base64 = read.nextLine();
String code=""; int track = 0 ;
int lineLength=50;
for(int i=0 ;i<base64.length();i++){
if (track!=lineLength){
code += base64.charAt(i);
track++;
}else {
code += base64.charAt(i);
code +="\n";
track=0;
}
}
System.out.println("\nOutput:\n\n"+code);
}
}
view raw WrapText.java hosted with ❤ by GitHub

What that code does is iterate through the string character by character and break whenever a character passes the limit which is "lineLength" variable.

The results:

split a string into fixed length rows

Post a Comment

0 Comments