Reputation: 183
I want to split a string (line) by the first whitespace, but only the first.
StringTokenizer linesplit = new StringTokenizer(line," ");
Take for example "This is a test". Then I want the strings to be "This" and "is a test". How could I use StringTokenizer or is there a better option?
Upvotes: 3
Views: 158
Reputation: 36742
You will have to right your own logic for this. Something like this :
String[] linesplit = line.split(" ");
String firstString = linesplit[0];
String secondString = new String();
for(for int i=1; i< linesplit.length; i++)
{
if(i==1)
{
secondString = linesplit[i];
}
else if(i != linesplit.length-1)
{
secondString = seconString + " " + linesplit[i];
}
else
{
secondString = seconString + linesplit[i] + " ";
}
}
Upvotes: 1
Reputation: 4067
String.split(pattern,resultlength) does it. use:
String[] splitted = line.split(" ",2);
the ',2' parameter means that the resulting Array maximum size is 2.
Upvotes: 5
Reputation: 136022
you can use split
String[] a = s.split("(?<=^\\S+)\\s");
Upvotes: 2
Reputation: 4956
You can do something like this:
String firstPart = line.substring(0, line.indexOf(" "));
String secondPart = line.substring(line.indexOf(" ")+1);
Check docs: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Upvotes: 2