I want to split a string after a specific length without cut any words, not equal String

Abdul Rashid A :

I want to split a string Like 'Rupees Two Hundred Forty One and Sixty Eight only' when its length is at 35, I want to split this string in 2. I tried this code to split the string.

String text = "Rupees Two Hundred Forty One and Sixty Eight only";
List<String> parts = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += 35) {
    parts.add(text.substring(i, Math.min(length, i + size)));

but the output is like this.

[Rupees Two Hundred Forty One and Si, xty Eight only]

But I want to split the string like this.

[Rupees Two Hundred Forty One and, Sixty Eight only]

There is no cut word when splitting the string. The string varies every time according to the bill amount.

WJS :

You may not be able to do it exactly. But use String.indexOf() to find the first space starting at 35. Then use the substring method to divide the string.

      String text = "Rupees Two Hundred Forty One and Sixty Eight only";
      int i = text.indexOf(" ", 35);
      if (i < 0) {
         i = text.length();
      }
      String part1 = text.substring(0,i).trim();
      String part2 = text.substring(i).trim();

Here is an alternative method. It has not been fully checked for border cases.

      String[] words = text.split(" ");
      int k;
      part1 = words[0];
      for (k = 1; k < words.length; k++) {
         if (part1.length() >= 35 - words[k].length()) {
            break;
         }
         part1 += " " + words[k];
      }
      if (k < words.length) {
         part2 = words[k++];
         while (k < words.length) {
            part2 += " " + words[k++];
         }
      }
      System.out.println(part1);
      System.out.println(part2);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=163894&siteId=1