开发者

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

开发者 https://www.devze.com 2023-01-20 14:46 出处:网络
Have following Java code,that creates StringBuilder with \"\\n\",i.e. carriage return delimiters: while (scanner.hasNextLine()){

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开发者_JAVA技巧 String(line) had "\n" symbol.

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

thanks.


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.


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)


You could build the result without a newline to get rid of:

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


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


Instead of having to remove it you could simply never add it.

while (scanner.hasNextLine()) {
    if (sb.length()>0) sb.append("\n");
    sb.append(scanner.nextLine());
}


bool isFirst = true;
while (scanner.hasNextLine()){
  if(!isFirst)
    sb.append("\n"));
  else
    isFirst = false;

  sb.append(scanner.nextLine());

}


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

精彩评论

暂无评论...
验证码 换一张
取 消