I'm new to Coding area I apologize if this Question might have asked previously. I'm Trying to Achieve like this . Suppose i have a Paragraph or Line which is more than 64 characters like this I've been using the Lumia 822 for over a month now and I noticed that the moment I reach over 70 characters
At 60th Character we have word noticed so it should be pushed to next line. Expected output.
I've been using the Lumia 822 for over a month now and I noticed that the moment I reach over 70 characters
Could you please help me out how to achieve this. I have used String Tokenizer and substr() but didnt worked.
Please give your Valuable Suggestions.
Thanks.
A very simple solution:
public String appendNewLine(String text, int max) {
int count = 0;
StringBuilder output = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (count >= max && c == ' ') {
count = 0;
output.append("\n");
} else {
output.append(c);
}
count++;
}
return output.toString();
}
This code will ensure each line is strictly less than or equal to splitLen
. Any words coming after will be moved to next line.
You can adjust the line width using splitLen
argument. I have tried to cover couple of scenarios. If anything missing, kindly point out.
public String splitString(String s, int splitLen){
StringBuilder sb = new StringBuilder();
int splitStart = 0;
while(splitStart < s.length()){
int splitEnd = splitStart + splitLen;
splitEnd = splitEnd > s.length() ? s.length() : splitEnd; // avoid overflow
int spaceIndex = s.substring(splitStart, splitEnd)
.lastIndexOf(" ");
// look for lasts space in line, except for last line
if(spaceIndex != -1 && splitEnd != s.length()){
splitEnd = splitStart + spaceIndex;
}
// else (no space in line), split word in two lines..
sb.append(s.substring(splitStart, splitEnd))
.append(System.lineSeparator());
// if ends with space, skip space in next line
splitStart = splitEnd + (spaceIndex != -1 ? 1 : 0);
}
return(sb.toString());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.