Split string into individual words Java

后端 未结 12 1228
既然无缘
既然无缘 2020-12-02 13:19

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.

相关标签:
12条回答
  • 2020-12-02 13:38

    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.

    0 讨论(0)
  • 2020-12-02 13:42

    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]);
    }
    
    0 讨论(0)
  • 2020-12-02 13:42

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

    String[] str = s.split("\\s+");
    
    0 讨论(0)
  • 2020-12-02 13:44

    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());
    }
    
    0 讨论(0)
  • 2020-12-02 13:44
    String[] str = s.split("[^a-zA-Z]+");
    
    0 讨论(0)
  • 2020-12-02 13:46

    Use split()

    String words[] = stringInstance.split(" ");
    
    0 讨论(0)
提交回复
热议问题