在遍历循环时,如何在StringBuilderString中的中间添加新行


StringBuilder sbText = new StringBuilder();
//After some lines 
sbText.append(FileUtils.readFileToString(f, encoding: "utf-8"));
sbText.append("nn=======================nn");

显示的内容包含文本。。。。

Dear Name          //there is 1 n
Bahuguna Marg,    //there is also 1 n
Bhagwanpur,       //there is also nn

Details : Claim     //there is also nn
Dear Rob,         //there is also nn
Thank you for the claim rob.       //here is 1 n ( I want 2 n here )
We have the block here.....................
........................      //there is also 1 n ( I want 2 n here )

如何解决这个问题。。。。字符串属于StringBuilder。。。。

我尝试的是,我将在字符串中迭代一个循环,如果charAt(I(包含\n而charAt(I+1(不包含,那么我将在那里附加。。。。。

但它给了我一个例外";StringIndexOutOfBoundException";。

我的代码是->

String ns = "n";
for(int i = 0; i < sbText.length() ; i++)
{
if(sbText.charAt(i) == "n" && sbText.charAt(i+1) != "n")
{
sbText.append(ns,i,i+1);
}
}

对于任何涉及行尾的操作,请使用System.lineSeparator()

在调用sbText.append(ns, i, i+1)中,开始/结束索引应用于参数ns,因此当i > 0时,调用总是失败。此外,在检查charAt(i+1)时,您会扫描超过sbText的末尾。

目前还不清楚为什么您需要将n的实例加倍,但您可以更改逻辑,从最后向后扫描,以确保不会两次处理相同的n

for(int max = sbText.length() - 1, i = max; i >= 0; i--) {
if(sbText.charAt(i) == 'n' && (i == max || sbText.charAt(i+1) != 'n')) {
sbText.insert(i, ns);
}
}

请注意,上面的操作不是很有效,因为每次对insert的调用都会移动StringBuilder的所有剩余字符。

如果你的文本大小很小,你可以打电话给:

String doubledNL = sbText.toString()
.replace(System.lineSeparator(), System.lineSeparator()+System.lineSeparator());

最新更新