Reputation: 1
How can I left align text in java eclipse console. For example line must be 50 character and also word should not divide. I tried above code but I think it is not working. How can I do that?
public void Left(String str){
if(str.length()>50){
int cursor = 0;
int k = 0;
for (int i = 0; i < str.length(); i++,cursor++) {
if(cursor%50 == 0){
//if(str.charAt(cursor)!=' ')
for (int index = i; index > 0; index--) {
if(str.charAt(index) == 32){
String left = str.substring(0, index);
String right = str.substring(index+1, str.length());
str = left+"\n"+right;
int lineLength = str.split("\n")[k].length();
int d = 50-lineLength;
while(d-- != 0){
String left2 = str.substring(k*50, (k*50)+lineLength);
String right2 = str.substring(lineLength++, str.length());
str = left2+" "+right2;
}
k++;
break;
}
}
}
}
}
System.out.println(str);
}
Upvotes: 0
Views: 535
Reputation: 36339
The easiest would be to split on whitespace, then looping through the array, printing each word followed by a space or a newline whenever the line length would be too wide with the next word. Take care of words that are longer than the line limit, and print them on its own line.
Upvotes: 0