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 ?
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 ?
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();
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
.
After getting the string from string buffer sbString.replaceAll("[\n\r]*$", "") will do the job for you
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