1

文字列を ArrayList に分割したいと思います。例:

文字列 = 「質問への回答を希望しますか」の結果は金額 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を使用した1行のソリューションを破棄します。(開示:私は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 に答える