Mittwoch, 8. April 2009

A way to split String's with StringTokenizer

Lets say we want to split a sentence into words and save it in an array. Of course there are several ways to do this here i'm gonna present you one enjoy.

public static void main(String[] args) {
String sentence = "Can you split me please ?";
String[] words = splitStringToStringArray(sentence);
for (String word : words){
System.out.println(word);
}
}

public static String[] splitStringToStringArray(String string) {
StringTokenizer str = new StringTokenizer(string);
String[] result = new String[str.countTokens()];
for(int e=0;str.hasMoreElements();e++) {
result[e] = str.nextToken();
}
return result;
}

Pretty neat ain't it ? Feel free to leave a comment on it.