Remove last line from a StringBuilder without knowing the number of characters

18.6k views Asked by At

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

Example:

Hello, how are you?
Fine thanks!
Ok, Perfect...

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

3

There are 3 answers

5
ericbn On BEST ANSWER
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-empty 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

0
user140547 On

Depending on how your Strings are constructed and what your goal is, it may be easier to not add the last line to the StringBuilder instead of removing it.

0
Thomas On

Depending on your performance requirements there are a few options:

One option, as already mentioned by others, would be to look for the last index of \n and if it is the last character recursively look for the next to last index etc. until you hit the last non-empty line.

Another option would be to use regular expressions to look for that:

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 whitespace as empty you could change the expression to \n[^\n]+[\s\n]+$ (as a Java string that would be "\n[^\n]+[\\s\n]+$") .