Placement Prep

Count Vowels, Consonants, Digits and Special Characters in a String

Programs in Python, C, and Java to count vowels, consonants, digits, and special characters in a string. Algorithm, code, and traced outputs included.

By FACE Prep Team 5 min read
string-programs python c-programming java algorithms placement-prep data-structures

Counting vowels, consonants, digits, and special characters in a string is a single-pass classification problem that shows up in TCS NQT, Infosys InfyTQ, and Wipro NLTH coding rounds.

The algorithm is identical across all languages: loop once through each character, decide its category, increment the right counter. Done. One pass, five counters.

The Problem and Character Classification Rules

Given a string, count how many characters fall into each of these five buckets:

  • Vowels: a, e, i, o, u — uppercase and lowercase both count.
  • Consonants: any letter that is not a vowel (b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z — both cases). ‘y’ is a consonant here.
  • Digits: 0 through 9.
  • Spaces: the space character ’ ’ (and tab \t if you want to be thorough; placement tests usually restrict to the space character).
  • Special characters: everything else — punctuation, symbols (@, #, $, %, &, *).

Verified traced output for the sample string

Input: This program is very easy 2 complete

CategoryCharactersCount
Vowelsi, o, a, i, e, e, a, o, e, e10
ConsonantsT, h, s, p, r, g, r, m, s, v, r, y, s, y, c, m, p, l, t19
Spaces(6 spaces)6
Digits21
Special characters(none)0

Total characters: 36. Check: 10 + 19 + 6 + 1 + 0 = 36. Verified.

Algorithm and Complexity

The procedure has four steps:

  • Step 1: Read the input string.
  • Step 2: Initialise five counters: vowels = consonants = digits = spaces = special = 0.
  • Step 3: For each character in the string, classify it and increment exactly one counter.
  • Step 4: Print all five counters.

Classification decision tree

character
  ├── isalpha() → True
  │   ├── lowercase(char) in {a, e, i, o, u} → vowels++
  │   └── otherwise → consonants++
  ├── isdigit() → True → digits++
  ├── isspace() → True → spaces++
  └── otherwise → special++

The time complexity is O(n), where n is the length of the string. Each character is visited exactly once. For space complexity, the algorithm uses five counters regardless of input size: O(1).

This classification logic is the same building block used in the sum-of-digits program (isolate a character, decide its value, accumulate) and in digit manipulation problems (examine each character, conditionally replace it).

Python Solution

Python’s built-in string methods handle all three classification checks. The key methods, documented in the Python 3 standard library, are str.isalpha(), str.isdigit(), and str.isspace().

def count_characters(s):
    vowels = consonants = digits = spaces = special = 0
    vowel_set = set("aeiouAEIOU")

    for ch in s:
        if ch.isalpha():
            if ch in vowel_set:
                vowels += 1
            else:
                consonants += 1
        elif ch.isdigit():
            digits += 1
        elif ch.isspace():
            spaces += 1
        else:
            special += 1

    return vowels, consonants, digits, spaces, special


# Driver code
s = input("Enter a string: ")
v, c, d, sp, sym = count_characters(s)
print(f"Vowels        : {v}")
print(f"Consonants    : {c}")
print(f"Digits        : {d}")
print(f"Spaces        : {sp}")
print(f"Special chars : {sym}")

Traced output for the sample

  • Input: This program is very easy 2 complete
  • Output:
    • Vowels: 10
    • Consonants: 19
    • Digits: 1
    • Spaces: 6
    • Special chars: 0

C and Java Solutions

C solution using ctype.h

The C standard library’s ctype.h provides isalpha(), isdigit(), and isspace(). Use tolower() before checking for vowels to collapse the case comparison to five characters.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

void count_characters(const char *s) {
    int vowels = 0, consonants = 0, digits = 0, spaces = 0, special = 0;
    const char *vowel_list = "aeiou";

    for (int i = 0; s[i] != '\0'; i++) {
        char ch = s[i];
        if (isalpha(ch)) {
            if (strchr(vowel_list, tolower(ch)) != NULL)
                vowels++;
            else
                consonants++;
        } else if (isdigit(ch)) {
            digits++;
        } else if (isspace(ch)) {
            spaces++;
        } else {
            special++;
        }
    }

    printf("Vowels        : %d\n", vowels);
    printf("Consonants    : %d\n", consonants);
    printf("Digits        : %d\n", digits);
    printf("Spaces        : %d\n", spaces);
    printf("Special chars : %d\n", special);
}

int main() {
    char s[201];
    printf("Enter a string (max 200 chars): ");
    fgets(s, sizeof(s), stdin);
    count_characters(s);
    return 0;
}

Note: fgets includes the trailing newline \n in the buffer. The isspace() call will count it as a space. Trim the trailing newline before passing to count_characters if you want clean output.

Java solution using the Character class

Java’s Character class provides Character.isLetter(), Character.isDigit(), and Character.isWhitespace(), the exact equivalents of the Python and C approaches.

import java.util.Scanner;

public class CountCharacters {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String s = sc.nextLine();

        int vowels = 0, consonants = 0, digits = 0, spaces = 0, special = 0;
        String vowelSet = "aeiouAEIOU";

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (Character.isLetter(ch)) {
                if (vowelSet.indexOf(ch) != -1)
                    vowels++;
                else
                    consonants++;
            } else if (Character.isDigit(ch)) {
                digits++;
            } else if (Character.isWhitespace(ch)) {
                spaces++;
            } else {
                special++;
            }
        }

        System.out.println("Vowels        : " + vowels);
        System.out.println("Consonants    : " + consonants);
        System.out.println("Digits        : " + digits);
        System.out.println("Spaces        : " + spaces);
        System.out.println("Special chars : " + special);
    }
}

Common Variations and Edge Cases

Placement coding judges test several variations on this problem. Know the differences before the test.

Variation 1: Spaces counted as special characters

Some problem statements don’t separate spaces from symbols. When the problem says “count special characters” and includes spaces in that bucket, remove the isspace branch and let spaces fall through to the special counter. Reread the problem statement before coding.

Variation 2: Case-insensitive alphabet check

If the problem says “treat uppercase and lowercase as the same”, convert the entire input to lowercase first before the loop: s = s.lower() in Python, tolower(s[i]) in C. This simplifies the vowel check to a 5-char set.

Variation 3: No space counter requested

The original version of this problem listed five categories including spaces. Some coding rounds simplify to four: vowels, consonants, digits, special (where special absorbs spaces). The solution above handles both; just drop or merge the spaces counter as required.

Variation 4: Unicode input on competitive judges

ASCII-only inputs are standard on Indian placement judges (TCS iON, HirePro, eLitmus). Python 3’s isalpha() returns True for accented Unicode letters like ‘é’ or ‘ñ’, which could miscategorise them as vowels or consonants rather than special characters. If the judge restricts input to ASCII, this doesn’t matter. If not, add a guard: only apply isalpha() or isdigit() when ord(ch) < 128.

Quick edge-case table

InputExpected output
"" (empty string)All counters: 0
"12345"Digits: 5, rest: 0
" " (5 spaces)Spaces: 5, rest: 0
"@#$%^"Special: 5, rest: 0
"AEIOUaeiou"Vowels: 10, rest: 0
"bcdfg"Consonants: 5, rest: 0

The five-counter loop in this problem is structurally the same as the character-classification pass inside a tokenizer: read a unit, decide its class, route it to a bucket. TinkerLLM builds on that intuition: it lets you go from hand-coded classifiers to calling production LLM APIs at ₹299, using the same decision logic at a billion-token scale rather than a 200-character string.

Primary sources

Frequently asked questions

Does 'y' count as a vowel or consonant in this program?

Consonant. Standard classification for this problem is: vowels are a, e, i, o, u (both cases). Every other alphabetic character, including 'y' and 'Y', is counted as a consonant.

What is the time and space complexity of this solution?

O(n) time where n is the length of the string — the loop visits each character exactly once. Space complexity is O(1) — only five integer counters are needed regardless of input length.

How does the Python solution handle uppercase vowels?

The vowel set 'aeiouAEIOU' includes both cases directly. Alternatively, call lower() on the character before testing: if ch.lower() in 'aeiou'. Both approaches produce identical counts.

What counts as a special character in this problem?

Any character that is not a letter (a to z, A to Z), digit (0 to 9), or space. Common examples: @, #, $, %, &, *, (, ), -, +, and punctuation marks like . and ,. In the variant where spaces are counted separately, they are not in the special-character bucket.

Does Python's str.isalpha() return True for accented letters like é?

Yes, in Python 3, str.isalpha() returns True for any Unicode alphabetic character. Placement test judges usually restrict inputs to ASCII printable characters, so this rarely matters in practice. To be safe, add a guard: if ord(ch) is greater than 127, treat the character as special.

What output does the program give for a string with no vowels, like 'bcdfg'?

Vowels: 0, Consonants: 5, Digits: 0, Spaces: 0, Special characters: 0.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF