java check if string contains multiple words

java check if string contains multiple words

To check if a string contains multiple words in Java, you can use the split method of the String class to split the string into an array of words, and then check the length of the array.

Here's an example of how to use the split method to check if a string contains multiple words:

re‮ot ref‬:lautturi.com
public class Main {
  public static void main(String[] args) {
    String str = "This is a test string";
    String[] words = str.split("\\s+");  // split on one or more white space characters

    if (words.length > 1) {
      // string contains multiple words
    } else {
      // string contains a single word
    }
  }
}

In this example, the split method is used to split the string "This is a test string" into an array of words using a regular expression that matches one or more white space characters. The length property of the array is then used to check if the string contains more than one word.

You can use a similar approach to split the string on any other delimiter, such as a comma or a colon, by replacing the regular expression in the split method with the appropriate delimiter.

Note that the split method returns an array of substrings, with each element in the array representing a word in the original string. If you need to check if the string contains multiple words regardless of whether they are separated by white space or any other delimiter, you can use a different approach, such as iterating through the array.

Created Time:2017-11-03 00:14:49  Author:lautturi