Java – deletes the last line from StringBuilder without knowing the number of characters
•
Java
I wonder if there is a simple way to delete the last line from the StringBuilder object without knowing the number of characters in the last line
Example:
I want to delete "OK, perfect..."
Solution
StringBuilder sb = new StringBuilder("Hello,how are you?\nFine thanks!\nOk,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
Editor: if you want to delete the last non empty line
StringBuilder sb = new StringBuilder( "Hello,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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码