2012-04-19 36 views
1

我想將字符串拆分爲ArrayList。 例子:根據選定的字符數量在ArrayList中拆分字符串

字符串= 「你想有你的問題的回答」 結果與量3:WOU - > ArrayList中,LD - > ArrayList中,你 - > ArrayList中,...

量是一個預定義的變量。

至今:

public static void analyze(File file) { 

    ArrayList<String> splittedText = new ArrayList<String>(); 

    StringBuffer buf = new StringBuffer(); 
    if (file.exists()) { 
     try { 
      FileInputStream fis = new FileInputStream(file); 
      InputStreamReader isr = new InputStreamReader(fis, 
        Charset.forName("UTF-8")); 
      BufferedReader reader = new BufferedReader(isr); 
      String line = ""; 
      while ((line = reader.readLine()) != null) { 
       buf.append(line + "\n"); 
       splittedText.add(line + "\n"); 
      } 
      reader.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    String wholeString = buf.toString(); 

    wholeString.substring(0, 2); //here comes the string from an txt file 
} 
+1

那麼什麼是你的具體問題? (編譯/運行時)錯誤?輸出錯誤? ... – 2012-04-19 19:23:15

回答

0

您正在將每行添加到您的數組列表中,並且聽起來不像您想要的那樣。我認爲你正在尋找的東西是這樣的:

int i = 0; 
for(i = 0; i < wholeString.length(); i +=3) 
{ 
    splittedText.add(wholeString.substring(i, i + 2)); 
} 
if (i < wholeString.length()) 
{ 
    splittedText.add(wholeString.substring(i)); 
} 
2

「正常」的方式來做到這一點是你所期望的:

List<String> splits = new ArrayList<String>(); 
for (int i = 0; i < string.length(); i += splitLen) { 
    splits.add(string.substring(i, Math.min(i + splitLen, string.length())); 
} 

我會扔了一個在線解決方案與Guava,雖然。 (披露:我貢獻番石榴)

return Lists.newArrayList(Splitter.fixedLength(splitLen).split(string)); 

僅供參考,您應該使用StringBuilder,而不是StringBuffer,因爲它看起來並不像你需要線程安全。

1

你可以不用串這樣的電話:

String str = "Would you like to have responses to your questions"; 
Pattern p = Pattern.compile(".{3}"); 
Matcher matcher = p.matcher(str); 
List<String> tokens = new ArrayList<String>(); 
while (matcher.find()) 
    tokens.add(matcher.group()); 
System.out.println("List: " + tokens); 

OUTPUT:

List: [Wou, ld , you, li, ke , to , hav, e r, esp, ons, es , to , you, r q, ues, tio] 
相關問題