-1

我需要实现的是:

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

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

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 个字符,因此将字符串分成数组中的两行。我已经在代码中删除了它,以尝试首先解决数组中的另一个问题。

4

1 回答 1

0

我有一个类似的问题,并尝试这样:

public void splitString(字符串输入,列表结果){

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

}

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

于 2013-11-21T15:20:46.347 回答