5

StringBuffer をループするときに、新しい行の開始位置を取得する必要があります。文字列バッファに次のドキュメントがあるとします

"This is a test
Test
Testing Testing"

"test"、"Test"、"Testing" の後に新しい行があります。

次のようなものが必要です:

for(int i =0;i < StringBuffer.capacity(); i++){
if(StringBuffer.chatAt(i) == '\n')
    System.out.println("New line at " + i);

}

「\n」は文字ではないため、機能しないことはわかっています。何か案は?:)

ありがとう

4

3 に答える 3

8

ループを次のように単純化できます。

StringBuffer str = new StringBuffer("This is a\ntest, this\n\nis a test\n");

for (int pos = str.indexOf("\n"); pos != -1; pos = str.indexOf("\n", pos + 1)) {
  System.out.println("\\n at " + pos);
}
于 2011-10-04T14:35:06.000 に答える
2
System.out.println("New line at " + stringBuffer.indexOf("\n"));

(もうループは必要ありません)

于 2011-10-04T14:28:02.743 に答える
1

あなたのコードは、いくつかの構文変更でうまく動作します:

public static void main(String[] args) {
    final StringBuffer sb = new StringBuffer("This is a test\nTest\nTesting Testing");

    for (int i = 0; i < sb.length(); i++) {
        if (sb.charAt(i) == '\n')
            System.out.println("New line at " + i);
    }
}

コンソール出力:

New line at 14
New line at 19
于 2011-10-04T14:32:46.017 に答える