count the number of words in a string java code example

Example 1: count the number of words in a string java

public static void main(String[] args)
    { 
        //return the number of words in a string 
        
       String example = "This is a good exercise"; 
       
       int length = example.split(" ").length;
       
       System.out.println("The string is " + length + " words long.");
        
        
    }

Example 2: java count frequency of characters in a string

public class Frequency   
{  
     public static void main(String[] args) {  
        String str = "picture perfect";  
        int[] freq = new int[str.length()];  
        int i, j;  
          
        //Converts given string into character array  
        char string[] = str.toCharArray();  
          
        for(i = 0; i <str.length(); i++) {  
            freq[i] = 1;  
            for(j = i+1; j <str.length(); j++) {  
                if(string[i] == string[j]) {  
                    freq[i]++;             
                    //Set string[j] to 0 to avoid printing visited character  
                    string[j] = '0';  
                }  
            }  
        }  
        //Displays the each character and their corresponding frequency  
        System.out.println("Characters and their corresponding frequencies");  
        for(i = 0; i <freq.length; i++) {  
            if(string[i] != ' ' && string[i] != '0')  
                System.out.println(string[i] + "-" + freq[i]);  
        }  
    }  
}

Example 3: how to count words in string in java

String str = "I am happy and why not
  and why are you not happy and you should be";
        String [] arr = str.split(" ");
        Map<String, Integer> map = new HashMap<>();

        for (int i=0 ; i < arr.length ; i++){
                if (!map.containsKey(arr[i])){
                    map.put(arr[i],1);
                } else{
                    map.put(arr[i],map.get(arr[i])+1);
                }
        }
        for(Map.Entry<String, Integer> each : map.entrySet()){

  System.out.println(each.getKey()+" occures " + each.getValue() + " times");
        }

Example 4: how to count number of words in a string

String name = "Carmen is a fantastic play"; //arbitrary sentence
        
        int numWords = (name.split("\\s+")).length; //split string based on whitespace
                                                //split returns array - find legth of array
        
        System.out.println(numWords);

Tags:

C Example