I would like to know how to split up a large string into a series of smaller strings or words. For example:
I want to walk my dog.
As a more general solution (but ASCII only!), to include any other separators between words (like commas and semicolons), I suggest:
String s = "I want to walk my dog, cat, and tarantula; maybe even my tortoise.";
String[] words = s.split("\\W+");
The regex means that the delimiters will be anything that is not a word [\W], in groups of at least one [+]. Because [+] is greedy, it will take for instance ';' and ' ' together as one delimiter.
You can use split(" ")
method of the String
class and can get each word as code given below:
String s = "I want to walk my dog";
String []strArray=s.split(" ");
for(int i=0; i<strArray.length;i++) {
System.out.println(strArray[i]);
}
This regex will split word by space like space, tab, line break:
String[] str = s.split("\\s+");
Yet another method, using StringTokenizer :
String s = "I want to walk my dog";
StringTokenizer tokenizer = new StringTokenizer(s);
while(tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
String[] str = s.split("[^a-zA-Z]+");
Use split()
String words[] = stringInstance.split(" ");