I need to split my String by spaces. For this I tried:
str = \"Hello I\'m your String\";
String[] splited = str.split(\" \");
But it doesn\
An alternative way would be:
import java.util.regex.Pattern;
...
private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split
Saw it here
if somehow you don't wanna use String split method then you can use StringTokenizer class in Java as..
StringTokenizer tokens = new StringTokenizer("Hello I'm your String", " ");
String[] splited = new String[tokens.countTokens()];
int index = 0;
while(tokens.hasMoreTokens()){
splited[index] = tokens.nextToken();
++index;
}
Since it's been a while since these answers were posted, here's another more current way to do what's asked:
List<String> output = new ArrayList<>();
try (Scanner sc = new Scanner(inputString)) {
while (sc.hasNext()) output.add(sc.next());
}
Now you have a list of strings (which is arguably better than an array); if you do need an array, you can do output.toArray(new String[0]);
What you have should work. If, however, the spaces provided are defaulting to... something else? You can use the whitespace regex:
str = "Hello I'm your String";
String[] splited = str.split("\\s+");
This will cause any number of consecutive spaces to split your string into tokens.
As a side note, I'm not sure "splited" is a word :) I believe the state of being the victim of a split is also "split". It's one of those tricky grammar things :-) Not trying to be picky, just figured I'd pass it on!
Simple to Spit String by Space
String CurrentString = "First Second Last";
String[] separated = CurrentString.split(" ");
for (int i = 0; i < separated.length; i++) {
if (i == 0) {
Log.d("FName ** ", "" + separated[0].trim() + "\n ");
} else if (i == 1) {
Log.d("MName ** ", "" + separated[1].trim() + "\n ");
} else if (i == 2) {
Log.d("LName ** ", "" + separated[2].trim());
}
}
Use Stringutils.split()
to split the string by whites paces. For example StringUtils.split("Hello World")
returns "Hello" and "World";
In order to solve the mentioned case we use split method like this
String split[]= StringUtils.split("Hello I'm your String");
when we print the split array the output will be :
Hello
I'm
your
String
For complete example demo check here