Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,941 questions

51,877 answers

573 users

How to count the number of vowels consonants digits spaces and special characters in a string with Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "Java SE 16 (March 16, 2021) - Java is object-oriented programming language";
        int vowels = 0, consonants = 0, digits = 0, spaces = 0, special_characters = 0;

        s = s.toLowerCase();
        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
    
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vowels++;
            } else if (ch >= 'a' && ch <= 'z') {
                        consonants++;
                    } else if (ch >= '0' && ch <= '9') {
                                digits++;
                            } else if (ch == ' ') {
                                        spaces++;
                                    } else 
                                        special_characters++;
                                    
        }
    
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
        System.out.println("Digits: " + digits);
        System.out.println("Spaces: " + spaces);
        System.out.println("Special Characters: " + special_characters);
    }
}





/*
run:
      
Vowels: 20
Consonants: 30
Digits: 8
Spaces: 11
Special Characters: 5
      
*/

 



answered Jan 13, 2022 by avibootz
...