How to split line from first space only in Java

I tried to split the string using string.Index and string.length, but I get an error that the string is out of range. How can i fix this?

while (in.hasNextLine()) { String temp = in.nextLine().replaceAll("[<>]", ""); temp.trim(); String nickname = temp.substring(temp.indexOf(' ')); String content = temp.substring(' ' + temp.length()-1); System.out.println(content); 
+14
source share
3 answers

It should be something like this:

 String nickname = temp.substring(0, temp.indexOf(' ')); String content = temp.substring(temp.indexOf(' ') + 1); 
+5
source

Use the java.lang.String split function with a limit.

 String foo = "some string with spaces"; String parts[] = foo.split(" ", 2); System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1])); 

You'll get:

 cr: some, cdr: string with spaces 
+25
source
 string.split(" ",2) 

split accepts an input limit that limits the number of uses of the template.

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)

+5
source

Source: https://habr.com/ru/post/1257347/


All Articles