Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove first line from a String containing XML?

Tags:

java

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

like image 943
user1114509 Avatar asked Dec 24 '11 11:12

user1114509


People also ask

How do I remove the first line of a string?

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);

How do I remove the beginning of a string in Java?

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.

How do I remove one character from a string?

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.


2 Answers

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.

like image 196
Sergey Kalinichenko Avatar answered Sep 24 '22 08:09

Sergey Kalinichenko


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.

like image 42
gdrt Avatar answered Sep 25 '22 08:09

gdrt