count the number of words in a string java

count the number of words in a string java

how to count number of words in a string

re‮l:ot ref‬autturi.com
/**
 * @author lautturi.com
 * Java example: count words in java string
 */

import java.util.*;

public class Lautturi {

	public static void main(String[] args) {

		String str = "hello lautturi java world!";

		int length = str.split(" ").length;
		//int length = str.split("\\s+").length;  // using regular expression

		System.out.println("The string has " + length + " words.");

	}
}

output:

The string has 4 words.
Created Time:2017-09-04 07:27:48  Author:lautturi