【问题标题】:Splitting a long string by last space, but no longer substrings then 132 characters按最后一个空格拆分长字符串,但不再是 132 个字符的子字符串
【发布时间】:2013-10-18 12:10:10
【问题描述】:

我需要实现的是:

  • 我有一个字符串,可以从输入中包含 0 个字符到 300 个字符。
  • 我需要将字符串拆分为一个数组,每行最多包含 132 个字符。
  • 我需要在最后一个空格处拆分字符串,从 132 倒数。
  • 下一行不应以空格开头。
  • 如果字符串少于 132 个字符,它应该发送整个/剩余的字符串。

我尝试了不同的 Java 代码,这些代码是在 Google 上找到的,并且我已经对其进行了修改以满足我的需要。得到了不同的结果,但它们似乎总是随着我在数组中的进一步下降而被抵消。

public void SplitString(String[] input, ResultList result, Container container) throws     StreamTransformationException{

int i = 0;
int start = 0;
int end = 0;

//loop through entire values in input array
for (int j=0; j<input.length; j++) { 
  if (input[j].length() == 0) {

       result.addValue("");

  }
else {
            //repeat for the length of each value
      for (i=0;i<input[j].length(); i=i+(input[j].lastIndexOf(" ",132))) {
           start =i;
           end =i+input[j].lastIndexOf(" ",132);

               if (input[j].length()> end) {
                   result.addValue(input[j].substring(start,end));
           }

           if (!(input[j].length()==0)){
                if (end >= input[j].length()) { 
                     end = end -input[j].lastIndexOf(" ",132);
                     result.addValue( input[j].substring(end,input[j].length()));
                }

           }      
         }
  }     
}

来回编辑我的代码,但这是“最后一个版本”。我知道这段代码不考虑字符串是否初始短于 132 个字符,因此将字符串分成数组中的两行。我已经在代码中删除了它,以尝试首先解决数组中的另一个问题。

【问题讨论】:

  • 所以请出示您的代码...
  • 对不起,忘记添加代码:(

标签: java string substring split


【解决方案1】:

我也遇到了类似的问题,试了一下:

public void splitString(String input, List result) {

String[] words = input.split(" ");

System.out.println(words.length);

String currentLine = "";
for (int i = 0; i < words.length; i++) {
    String word = words[i];
    if ((currentLine.length() + word.length()) < 132) {
        currentLine += " " + word;
    } else {
        result.add(currentLine);
        currentLine = word;
    }
}

result.add(currentLine);

}

它有效,但这种方式要求您的输入字符串包含空格。 所以请随时改进它...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2017-04-23
    • 2022-10-19
    相关资源
    最近更新 更多