Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 339
sergionni Avatar asked Oct 16 '10 16:10

sergionni


2 Answers

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.

like image 71
Nikita Rybak Avatar answered Oct 13 '22 00:10

Nikita Rybak


If you're working with a small enough number of lines, you can put all the lines in a List<String> and then use StringUtils.join(myList, "\n");

Another option is to trim() the resulting string.

Update after discovering guava's neat Joiner class:

Joiner.on('\n').join(myList)

like image 37
oksayt Avatar answered Oct 12 '22 23:10

oksayt