How to count the words in a string in Java

5 Answers

0 votes
public class WordCounter {

    public static void main(String[] args) {
        String s = "Java Programming Language";
        
        int wordCount = countWords(s);
        
        System.out.println("Words = " + wordCount);
    }

    // Function to count words in a string
    public static int countWords(String input) {
        String[] parts = input.split(" ");
        
        int count = 0;
        for (String word : parts) {
            if (!word.trim().equals("")) {
                count++;
            }
        }
        
        return count;
    }
}



/*
run:

Words = 3

*/


answered Oct 2, 2014 by avibootz
edited Nov 1, 2025 by avibootz
0 votes
public class WordCounter {

    public static void main(String[] args) {
        String s = "Java Programming Language";
        
        String[] words = s.split("\\W+");
 
        System.out.println("Words: " + words.length);
    }
}



/*
run:

Words = 3

*/

 



answered Nov 1, 2025 by avibootz
0 votes
public class WordCounter {
    public static int countWords(String s) {
        String[] words = s.trim().split("\\s+"); // Split by one or more whitespace characters
          
        return words.length;
    }
  
    public static void main(String[] args) {
        String s = "Java   Programming     Language";
          
        int wordCount = countWords(s);
          
        System.out.println("Words = " + wordCount);
    }
}
  
  
  
/*
run:
  
Words = 3
  
*/

 



answered Nov 1, 2025 by avibootz
edited Nov 3, 2025 by avibootz
0 votes
import java.util.Scanner;

public class WordCounter {
    public static int countWords(String input) {
        Scanner scanner = new Scanner(input);
        int count = 0;
        
        while (scanner.hasNext()) {
            scanner.next();
            count++;
        }
        
        scanner.close();
        
        return count;
    }

    public static void main(String[] args) {
        String s = "Java Programming Language";
        
        int wordCount = countWords(s);
        
        System.out.println("Words = " + wordCount);
    }
}



/*
run:

Words = 3

*/

 



answered Nov 1, 2025 by avibootz
0 votes
public class WordCounter {
    public static void main(String[] args) {
        String s = "Java is a general-purpose object-oriented programming language";
         
        String words[] = s.split("[ -]"); 
        // String words[] = s.split("-| "); 
         
        System.out.println("Words = " + words.length);
    }
}
 
 
 
/*
run:
 
Words = 9
 
*/


 



answered Nov 1, 2025 by avibootz
...