Remove last line from StringBuilder without knowing the number of characters

I want to know if there is a simple method to remove the last line from a StringBuilder object without knowing the number of characters in the last line.

Example:

Hi, how are you? Thank you very much!
Good perfect...

I want to remove "Ok, Perfect ..."

+3


source to share


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()); }

      

http://ideone.com/9k8Tcj

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()); }
}

      

http://ideone.com/AlzQe0

+9


source


Depending on how your lines are constructed and what your purpose is, it may be easier not to add the last line in StringBuilder

instead of removing it.



+3


source


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







All Articles