Split string into individual words Java

后端 未结 12 1229
既然无缘
既然无缘 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:46

    you can use Apache commons' StringUtils class

        String[] partsOfString = StringUtils.split("I want to walk my dog",StringUtils.SPACE)
    
    0 讨论(0)
  • 2020-12-02 13:48

    A regex can also be used to split words.

    \w can be used to match word characters ([A-Za-z0-9_]), so that punctuation is removed from the results:

    String s = "I want to walk my dog, and why not?";
    Pattern pattern = Pattern.compile("\\w+");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
    

    Outputs:

    I
    want
    to
    walk
    my
    dog
    and
    why
    not
    

    See Java API documentation for Pattern

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

    See my other answer if your phrase contains accentuated characters :

    String[] listeMots = phrase.split("\\P{L}+");
    
    0 讨论(0)
  • 2020-12-02 13:51

    Use split() method

    Eg:

    String s = "I want to walk my dog";
    String[] arr = s.split(" ");    
    
    for ( String ss : arr) {
        System.out.println(ss);
    }
    
    0 讨论(0)
  • 2020-12-02 14:00

    To include any separators between words (like everything except all lower case and upper case letters), we can do:

    String mystring = "hi, there,hi Leo";
    String[] arr = mystring.split("[^a-zA-Z]+");
    for(int i = 0; i < arr.length; i += 1)
    {
         System.out.println(arr[i]);
    }
    

    Here the regex means that the separators will be anything that is not a upper or lower case letter [^a-zA-Z], in groups of at least one [+].

    0 讨论(0)
  • 2020-12-02 14:00
    StringTokenizer separate = new StringTokenizer(s, " ");
    String word = separate.nextToken();
    System.out.println(word);
    
    0 讨论(0)
提交回复
热议问题