To count the number of words in a string in Java, you can use the split
method of the String
class to split the string into an array of words, and then use the length
property of the array to count the number of words.
Here is an example of how you can count the number of words in a string in Java:
String s = "The quick brown fox jumps over the lazy dog."; String[] words = s.split("\\s+"); int count = words.length; System.out.println("Number of words: " + count);Source:www.lautturi.com
This code defines a string called s
and splits it into an array of words using the split
method. The split
method takes a regular expression as an argument, and in this example, the regular expression "\s+" matches one or more consecutive white space characters. The split
method returns an array of strings, with each element of the array representing a word in the original string.
The length
property of the words
array gives the number of elements in the array, which is equal to the number of words in the original string. The code stores the number of words in a variable called count
and prints it to the console.
The output of this code will be:
Number of words: 9
Note that the split
method of the String
class takes a regular expression as an argument, so you can use it to split the string into an array of words based on more advanced patterns. For example, you can use a regular expression to split the string into an array of words based on punctuation marks or specific characters.
If you only want to split the string into an array of words based on white space characters, you can use the split
method with the string "\s+" as the argument. This regular expression will match one or more consecutive white space characters, including spaces, tabs, and newlines.