根据选定的字符数在ArrayList中拆分String

时间:2012-04-19 19:20:58

标签: java string arraylist split

我想将一个字符串拆分成一个ArrayList。 例如:

String =“你想回答你的问题” 数量为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
}

3 个答案:

答案 0 :(得分: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,因为它看起来不像您需要线程安全。

答案 1 :(得分: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]

答案 2 :(得分: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 ) );
}