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..."
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With