Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 949
Abdul Rashid A Avatar asked Oct 16 '22 11:10

Abdul Rashid A


1 Answers

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

like image 134
WJS Avatar answered Oct 27 '22 15:10

WJS