[Solved] How to split a string after a certain length? But it should be divided after word completion


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

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