StringTokenizer delimits once

I want to split a line (line) into the first space, but only the first.

StringTokenizer linesplit = new StringTokenizer(line," ");

Take, for example, "This is a test." Then I want the lines to be "This" and "This is a test." How can I use StringTokenizer or is there a better option?

+3
source share
4 answers

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

+2
source

String.split (pattern, resultlength) does this. Application:

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

The parameter ', 2' means that the total maximum size of the array is 2.

+5
source

split

String[] a = s.split("(?<=^\\S+)\\s");
+2

. - :

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] + " ";
    }
}
+1

All Articles