Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string from the first space occurrence only Java

Tags:

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

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); 
like image 237
Dimitrios Sria Avatar asked Sep 27 '16 19:09

Dimitrios Sria


People also ask

How do I split a string with first space?

Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.

How do you get the first element to split?

To split a string and get the first element of the array, call the split() method on the string, passing it the separator as a parameter, and access the array element at index 0 . For example, str. split(',')[0] splits the string on each comma and returns the first array element. Copied!

How do you break apart a string in Java?

split("-"); We can simply use a character/substring instead of an actual regular expression. Of course, there are certain special characters in regex which we need to keep in mind, and escape them in case we want their literal value. Once the string is split, the result is returned as an array of Strings.

What does split \\ s+ do in Java?

split("\\s+") will split the string into string of array with separator as space or multiple spaces. \s+ is a regular expression for one or more spaces.


2 Answers

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 will get:

cr: some, cdr: string with spaces 
like image 179
Steve Owens Avatar answered Sep 28 '22 07:09

Steve Owens


Must be some around this:

String nickname = temp.substring(0, temp.indexOf(' ')); String content = temp.substring(temp.indexOf(' ') + 1); 
like image 33
Alex Chermenin Avatar answered Sep 28 '22 05:09

Alex Chermenin