删除 Java 中 StringBuilder 末尾的几个“\r\n”或“\n”

Removing several "\r\n" or "\n" at the end of a StringBuilder in Java

我需要删除 StringBuilder 末尾的几个 'newline'。

我尝试了以下代码。

while(sb.lastIndexOf("\r\n") == sb.length()){
        sb.setLength(sb.length() - 1);
}

它不起作用。有人有什么建议吗?

您可以检查结尾 subSequence 是否等于您想要的子字符串 ("\r\n") 并使用 setLength 减少长度,例如

while (sb.subSequence(sb.length() - 2, sb.length()).equals("\r\n")) {
    sb.setLength(sb.length() - 2);
}

您也可以考虑致电 toString()trim()

String s = sb.toString().trim();

输出sb.lastIndexOf("\n\r")sb.length(),你会看到字符位置的不同。因此 while 条件不起作用。

还要记住:\n\r 可能是 \r\n

从字符串缓冲区中获取字符串后 sbString.replaceAll("[\n\r]*$", "") 将为您完成这项工作

   StringBuilder check=new StringBuilder("i am here \n\n\n\n");
    System.out.println(check+" "+check.length());
    Boolean checkexist=true;
    while(checkexist){
         if(check.lastIndexOf("\n")==check.length());{
            check.setLength(check.length()-1);
            if(check.lastIndexOf("\n")==-1){
                 System.out.println(check+" "+check.length());
                checkexist=false;
            }                   

         }

输出:

我在这里

14

我在这里 10

表示去掉字符串中所有\n后的字符串长度