1

我想将一个字符串拆分为一个 ArrayList。例子:

String = "Would you like to have answers to your questions" 结果为 3: Wou -> arraylist, ld -> arraylist, you -> 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
}
4

3 回答 3

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抛出一个单线解决方案。(披露:我为 Guava 做出了贡献。)

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

仅供参考,您可能应该使用StringBuilder而不是StringBuffer,因为它看起来不需要线程安全。

于 2012-04-19T19:23:16.567 回答
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);

输出:

List: [Wou, ld , you,  li, ke , to , hav, e r, esp, ons, es , to , you, r q, ues, tio]
于 2012-04-19T19:36:20.723 回答
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 ) );
}
于 2012-04-19T19:30:06.273 回答