What\'s the best way to remove the first word from a string in Java?
If I have
String originalString = \"This is a string\";
I want to r
You can use substring
removedWord = originalString.substring(0,originalString.indexOf(' '));
originalString = originalString.substring(originalString.indexOf(' ')+1);
You can check where is the first space character and seperate string.
String full = "Sample Text";
String cut;
int pointToCut = full.indexOf( ' ');
if ( offset > -1)
{
cut = full.substring( space + 1);
}
Simple.
String o = "This is a string";
System.out.println(Arrays.toString(o.split(" ", 2)));
Output :
[This, is a string]
EDIT:
In line 2 below the values are stored in the arr
array. Access them like normal arrays.
String o = "This is a string";
String [] arr = o.split(" ", 2);
arr[0] // This
arr[1] // is a string
For an immediate answer you can use this :
removeWord = originalString.substring(0,originalString.indexOf(' '));
originalString = originalString.substring(originalString.indexOf(' '));
Try this using an index var, I think it's quite efficient :
int spaceIdx = originalString.indexOf(" ");
String removedWord = originalString.substring(0,spaceIdx);
originalString = originalString.substring(spaceIdx);
Prior to JDK 1.7 using below method might be more efficient, especially if you are using long string (see this article).
originalString = new String(originalString.substring(spaceIdx));
You can use the StringTokenizer class.