Split string into individual words Java

Viewed 283892

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.

I want to have a string: "I", another string:"want", etc.

How would I do this?

15 Answers

This regex will split word by space like space, tab, line break:

String[] str = s.split("\\s+");

you can use Apache commons' StringUtils class

String[] partsOfString = StringUtils.split("I want to walk my dog", StringUtils.SPACE)
StringTokenizer separate = new StringTokenizer(s, " ");
String word = separate.nextToken();
System.out.println(word);

Java String split() method example

 public class SplitExample{  
        public static void main(String args[]){  
            String str="java string split method";  
            String[] words=str.split("\\s");//splits the string based on whitespace  
     
            for(String word:words){  
                System.out.println(word);  
            }  
        }
    }
class test{
           
    public static void main(String[] args){
                StringTokenizer st= new StringTokenizer("I want to walk my dog.");
                
                while (st.hasMoreTokens())
                    System.out.println(st.nextToken());
         
            }
        }

Using Java Stream API:

String sentence = "I want to walk my dog.";

Arrays.stream(sentence.split(" ")).forEach(System.out::println);

Output:

I
want
to
walk
my
dog.

Or

String sentence2 = "I want to walk my dog.";

Arrays.stream(sentence2.split(" ")).map(str -> str.replace(".", "")).forEach(System.out::println);

Output:

I
want
to
walk
my
dog
String[] str = s.split("[^a-zA-Z]+");
Related