Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string at a particular position in java

Tags:

java

text

Assume you have a string of the form "word1 word2 word3 word4". What is the simplest way to split it such that split[0] = "word1 word2" and split[1] = "word3 word4"?

EDIT: Clarifying

I want to split such that instead of having split[0] = "word1", I have the first 2 words (I agree it was not clear) and all the other words in split[1], ie on the second space

like image 310
giulio Avatar asked Dec 19 '22 07:12

giulio


1 Answers

I would use the String.substring(beginIndex, endIndex); and String.substring(beginIndex);

String a = "word1 word2 word3 word4";
int first = a.indexOf(" ");
int second = a.indexOf(" ", first + 1);
String b = a.substring(0,second);
String c = b.subString(second); // Only startindex, cuts at the end of the string

This would result in a = "word1 word2" and b = "word3 word4"

like image 104
Einar Sundgren Avatar answered Jan 02 '23 19:01

Einar Sundgren