Gracefully remove "\n" delimiter after last String within StringBuilder

sergionni picture sergionni · Oct 16, 2010 · Viewed 20k times · Source

Have following Java code,that creates StringBuilder with "\n",i.e. carriage return delimiters:

while (scanner.hasNextLine()){
    sb.append(scanner.nextLine()).append("\n");
}

It's occurred,that after last String(line) had "\n" symbol.

How to gracefully remove last "\n" from resulting StringBuilder object?

thanks.

Answer

Nikita Rybak picture Nikita Rybak · Oct 16, 2010

This has always worked for me

sb.setLength(sb.length() - 1);

Operation is pretty lightweight, internal value holding current content size will just be decreased by 1.

Also, check length value before doing it if you think buffer may be empty.