有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 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());