0

I need to remove several 'newline' at the end of my StringBuilder.

I tried the following code.

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

It's not working. Anyone have any tips ?

morgano
  • 17,210
  • 10
  • 45
  • 56
fmassica
  • 1,896
  • 3
  • 17
  • 22
  • If you are using Java 8, I'd recommend [`StringJoiner`](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html), if not, consider using `String#endsWith` – MadProgrammer May 01 '15 at 02:31
  • possible duplicate of [Remove String from StringBuilder](http://stackoverflow.com/questions/21408401/java-remove-string-from-stringbuilder) - see the accepted answer to this question to see how you can replace parts of your StringBuilder instance (with an empty string to remove). – Amos M. Carpenter May 01 '15 at 02:34

4 Answers4

3

You could check if the ending subSequence equals your desired substring ("\r\n") and reduce the length with setLength like

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

You might also consider calling toString() and trim()

String s = sb.toString().trim();
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Output sb.lastIndexOf("\n\r") and sb.length() and you'll see the difference in char positions. Therefore the while condition doesn't work.

Also remember: \n\r could be \r\n.

Amos M. Carpenter
  • 4,848
  • 4
  • 42
  • 72
Eugene S
  • 44
  • 3
0

After getting the string from string buffer sbString.replaceAll("[\n\r]*$", "") will do the job for you

Eranda
  • 1,439
  • 1
  • 17
  • 30
0
   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;
            }                   

         }

Output:

i am here

14

i am here 10

It shows the length of the string after removing all \n in the string

Mohan Raj
  • 1,104
  • 9
  • 17