2013-10-18 19 views
-1

我需要實現的是:分割的長字符串的最後空間,但不再那麼子132個字符

  • 我有一個字符串,它可以爲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個字符,因此將該字符串分爲兩行。我已經在代碼中刪除了這個,試圖首先解決數組中的其他問題。

+4

所以請顯示您的代碼... – home

+0

對不起,忘了添加代碼:( – user2894591

回答

0

我有類似的問題,並試圖像這樣:

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

}

它的工作原理,但這種方式需要,您輸入的字符串中包含空格。 因此,隨時提高它...

相關問題