I have a string which contains XML. I want to remove its first line and save it back to String.
How can I do that?
Thanks
Assuming there's a new line at the end of the string that you would like to remove, you can do this: s = s. substring(s. indexOf('\n')+1);
Since Strings are immutable in Java, you can't remove any character from it. However, you can create a new instance of the string without the first character. The standard solution to return a new string with the first character removed from it is using the substring() method with the beginning index 1.
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
Assuming there's a new line at the end of the string that you would like to remove, you can do this:
s = s.substring(s.indexOf('\n')+1);
When there are no new lines, s
would remain the same.
Technically, because Macs (up to OS 9) used to use \r
and as the accepted solution doesn't solve this, it would make sense to use:
s = s.substring(s.indexOf(System.getProperty("line.separator"))+1);
But as it was mentioned in the comments, when using this code you have to make sure you don't work e.g. on source code files with Unix
line endings on Windows
.
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