Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..."

like image 933
Local Hero Avatar asked Dec 08 '22 02:12

Local Hero


2 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-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

like image 60
ericbn Avatar answered Dec 11 '22 10:12

ericbn


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.

like image 24
user140547 Avatar answered Dec 11 '22 09:12

user140547