Remove last line from StringBuilder without knowing the number of characters
3 answers
StringBuilder sb = new StringBuilder("Hello, how are you?\nFine thanks!\nOk, Perfect...");
int last = sb.lastIndexOf("\n");
if (last >= 0) { sb.delete(last, sb.length()); }
EDIT: If you want to remove the last non-blank line, do
StringBuilder sb = new StringBuilder(
"Hello, how are you?\nFine thanks!\nOk, Perfect...\n\n");
if (sb.length() > 0) {
int last, prev = sb.length() - 1;
while ((last = sb.lastIndexOf("\n", prev)) == prev) { prev = last - 1; }
if (last >= 0) { sb.delete(last, sb.length()); }
}
+9
source to share
There are several options depending on your performance requirements:
One option, as others have mentioned, is to search for the last index \n
and, if it is the last character, recursively search for the next and last index, etc., until you hit the last non-blank line.
Another option is to use regular expressions to search:
StringBuilder sb = new StringBuilder("Hello, how are you?\nFine thanks!\nOk, Perfect...\n\n");
Pattern p = Pattern.compile("\n[^\n]+\n+$");
Matcher m= p.matcher( sb );
//if there is a last line that matches our requirements
if( m.find() ) {
sb.delete( m.start( 0 ), m.end( 0 ) );
}
If you consider the white space to be empty, you can change the expression to \n[^\n]+[\s\n]+$
(like a Java string that would "\n[^\n]+[\\s\n]+$"
).
+1
source to share