我想在特定长度后拆分一个字符串而不切割任何单词,不等于字符串

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

我想拆分一个字符串,比如 'Rupees Two Hundred Forty One and Sixty Eight only',当它的长度为 35 时,我想将这个字符串拆分为 2 个。我试过这个代码来拆分字符串。

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

但是输出是这样的

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

但是我想这样拆分字符串。

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

拆分字符串时没有切词。 字符串每次根据账单金额不同。

您可能无法完全做到。但是用String.indexOf()从35开始找第一个space,然后用substring的方法分字符串

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

这是另一种方法。尚未完全检查边界情况。

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

您可以找到 "and" 的索引并将字符串从 0 子串到 "and" 的索引。

 int i = text.indexOf("and") + 3;
 String part1 = text.substring(0,i);
 String part2 = text.substring(i).trim();

只需在i+35位置搜索喜欢的位置。需要考虑的一件事是,当没有这样的位置时应该发生什么,即一个词超过指定的大小。以下代码将强制执行大小限制,如果找不到合适的位置,则在单词中间中断:

List<String> parts = new ArrayList<>();
int size = 35, length = text.length();
for(int i = 0, end, goodPos; i < length; i = end) {
    end = Math.min(length, i + size);
    goodPos = text.lastIndexOf(' ', end);
    if(goodPos <= i) goodPos = end; else end = goodPos + 1;
    parts.add(text.substring(i, goodPos));
}

如果中断发生在 space 字符处,space 将从结果字符串中删除。

我会使用 StringBuilders 从头开始​​构建字符串。一个带有一些评论的例子:

    String text = "Rupees Two Hundred Forty One and Sixty Eight only For seven thousand chickens";
    String split[] = text.split(" "); // Split by space
    // One SB for each sentence
    StringBuilder sentence = new StringBuilder();
    // One SB for the total String
    StringBuilder total = new StringBuilder();
    for (int i = 0; i < split.length; i++) {
        String word = split[i];
        // Check if that words fits to sentence
        if (sentence.length() + word.length() <= 35) {
            sentence.append(word);
            sentence.append(" ");
        } else {
            total.append(sentence.toString().trim());
            total.append(", ");
            // Flush sentence to total and start next sentence
            sentence = new StringBuilder();
            sentence.append(word);
            sentence.append(" ");
        }
    }
    //Add any leftover
    if (sentence.length() > 0)
        total.append(sentence.toString().trim());
    System.out.println(total.toString());

输出到:

Rupees Two Hundred Forty One and, Sixty Eight only For seven thousand, chickens

我认为你可以使用 while 循环来计算包含最后一个 space 个字符的单词:

public static List<String> split(String str, int length) {
    List<String> res = new ArrayList<>();
    int prvSpace = 0;
    int from = 0;

    while (prvSpace < str.length()) {
        int pos = str.indexOf(' ', prvSpace + 1);

        if (pos == -1) {
            res.add(str.substring(from));
            prvSpace = str.length();
        } else if (pos - from < length)
            prvSpace = pos;
        else {
            res.add(str.substring(from, prvSpace));
            from = prvSpace + 1;
        }
    }

    return res;
}

演示:

in: "RupeesTwoHundredFortyOneandSixtyEightonly"
out: ["RupeesTwoHundredFortyOneandSixtyEightonly"]

in: "Rupees Two Hundred Forty One and Sixty Eight only"
out: ["Rupees Two Hundred Forty One and", "Sixty Eight only"]

我找到了使用 Apache commons-lang3 的替代方法:

import java.util.Arrays;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;

class Example {

    public static void main(String[] args) {
        String text = "Rupees Two Hundred Forty One and Sixty Eight only";
        String wrappedText = WordUtils.wrap(text, 35, "\n", false);
        String[] lines = StringUtils.split(wrappedText, "\n");
        System.out.println(Arrays.asList(lines));
        // Outputs [Rupees Two Hundred Forty One and, Sixty Eight only]
    }
}

注意。如果您的输入有换行符,最好将其删除。