java如何在遍历循环时在StringBuilder字符串之间添加新行?
StringBuilder sbText = new StringBuilder();
//After some lines
sbText.append(FileUtils.readFileToString(f, encoding: "utf-8"));
sbText.append("\n\n=======================\n\n");
显示的内容包含文本
Dear Name //there is 1 \n
Bahuguna Marg, //there is also 1 \n
Bhagwanpur, //there is also \n\n
Details : Claim //there is also \n\n
Dear Rob, //there is also \n\n
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的
我尝试的是在字符串中迭代一个循环,如果字符(I)包含\n而字符(I+1)不包含,那么我将在那里附加\n
但它给了我一个例外“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);
}
}
# 1 楼答案
对于任何涉及行尾的操作,请使用
System.lineSeparator()
在调用
sbText.append(ns, i, i+1)
中,开始/结束索引应用于参数ns
,因此调用在i > 0
时总是失败。在检查charAt(i+1)
时,还可以扫描sbText
的末尾尚不清楚为什么需要将
\n
的实例加倍,但可以将逻辑更改为从末尾向后扫描,以确保不会两次处理相同的\n
:请注意,上面的方法不是很有效,因为对
insert
的每次调用都会移动StringBuilder的所有剩余字符如果文本的大小很小,您可以调用: