3

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?

adrianp
  • 173
  • 1
  • 3
  • 17

4 Answers4

5

String.split(pattern,resultlength) does it. use:

String[] splitted = line.split(" ",2);

the ',2' parameter means that the resulting Array maximum size is 2.

pdem
  • 3,880
  • 1
  • 24
  • 38
2

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

FazoM
  • 4,777
  • 6
  • 43
  • 61
2

you can use split

String[] a = s.split("(?<=^\\S+)\\s");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

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] + " ";
    }
}
ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176