当循环遍历 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' 不是一个字符。有任何想法吗? :)
谢谢
最佳答案
您可以这样简化循环:
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);
}
关于java - 获取 Stringbuffer 中换行符开头的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7649412/