简体   繁体   中英

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)));
}

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

You can split this string into an array of words, then iterate over this array and use StringBuilder to append words to lines up to a certain length. Optionally, for each word, you can check whether at least half of this word fits into a line, and if not, then start a new line. Your code might look something like this:

String text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " +
        "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +
        "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris " +
        "nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in " +
        "reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla " +
        "pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " +
        "culpa qui officia deserunt mollit anim id est laborum.";

int length = 55;
StringBuilder builder = new StringBuilder();

ArrayList<String> lines = new ArrayList<>();
Arrays.stream(text.split("\\s+")).forEach(w -> {
    if (builder.length() + w.length() / 2 > length) {
        lines.add(builder.toString().trim());
        builder.delete(0, builder.length());
    }
    builder.append(w).append(" ");
});
lines.add(builder.toString().trim());

// output line by line
lines.forEach(System.out::println);

Output:

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM