Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split the string before the 2nd occurrence of a character in Java

I have:

1234 2345 3456 4567

When I try String.split(" ",2), I get:

{1234} , {2345 3456 4567}

But I need:

{1234},{2345}

I want only the first two elements. How do I implement this in Java?
Thanks in advance.

EDIT:This is just one line of a huge dataset.

like image 799
HackCode Avatar asked Jun 20 '14 10:06

HackCode


People also ask

How do you split a string on the first occurrence of certain characters?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you find second occurrence of a character in a string?

i.e. if a string contains the letter c at indices 1, 5 and 10 the results are as follows: =FIND("c",A1,1) will find the first c =FIND("c",A1,2) through =FIND("c",A1,5) will find the second c =FIND("c",A1,6) through =FIND("c",A1,10) will find the third c.

What does split \\ do in Java?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.


1 Answers

I assume you need first two string, then do the following:

    String[] res = Arrays.copyOfRange(string.split(" "), 0, 2);
like image 89
HJK Avatar answered Nov 09 '22 11:11

HJK