Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

java - How to split a string after a certain length? But it should be divided after word completion

I want to divide a string into a list of strings after a certain length. Example I want to divide a string after the 50th but if the 50th character word is not completed it should divide after word completion

List<String> remarksList = new ArrayList<>();
String remarks = "I want to split in to multiple strings after every" +
        " 50 charcters but if there any word not completed it should" +
        " be divded after word completion";
int length = remarks.length();
for (int i = 0; i < length; i += NoaConstant.ARRIVAL_FREE_TEXT_LENGTH) {
    remarksList.add(remarks.substring(i,
            Math.min(length, i + NoaConstant.ARRIVAL_FREE_TEXT_LENGTH)));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is one simple way to do it. It presumes that a space separates words. It works as follows:

  • find the index of the first space starting at the desired length of the string.
  • if the return value is -1 (no space found), use the string length.
  • get the substring from 0 to that index.
  • if that was the end of the string, then break.
  • else replace the starting text with the remainder of the string, skipping over the just found space.
String remarks = "I want to split in to multiple strings after every 50 charcters but if there any word not completed it should be divded after word completion";

int length = 50;
List<String> remarksList = new ArrayList<>();
for(;;) {
       int end = remarks.indexOf(" ", length);
       end = end >= 0 ? end : remarks.length();
       String substr = remarks.substring(0,end);
       remarksList.add(substr);
       if (end >= remarks.length()) {
           break;
       }
       remarks = remarks.substring(end+1);
}

remarksList.forEach(System.out::println);

Prints

I want to split in to multiple strings after every
50 charcters but if there any word not completed it
should be divded after word completion


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...