Count Character Occurrences in a String

Count Character Occurrences in a String in C++

In this exercise, you will write a C++ program that counts how many times a specific character appears in a given string. This is a fundamental exercise for understanding string traversal, character comparison, and the use of the string library.

String Logic

1. getline() Function

Unlike cin, getline() captures the entire line, including spaces, allowing us to process full sentences.

2. String Indexing

Strings in C++ are zero-indexed arrays of characters. We can access each character using the str[i] syntax.

3. Iteration Logic

A for loop combined with str.length() ensures we visit every element in the string exactly once.

Objective

  • 1. Prompt the user to input a full string (including spaces).
  • 2. Ask for the specific character to search for.
  • 3. Use a for loop to iterate through the string.
  • 4. Compare each index to the target character and increment a counter on match.

Example C++ Exercise

char_occurrence_counter.cpp String Manipulation
#include <iostream> // Include library for I/O
#include <string>   // Include library for string handling

using namespace std; // Use standard namespace

int main() {
    string str;    // Variable for the input string
    char ch;       // Character to search for
    int count = 0; // Accumulator for occurrences

    // Ask user for a string
    cout << "Enter a string: ";
    getline(cin, str); 

    // Ask user for the character
    cout << "Enter a character to search for: ";
    cin >> ch;

    // Loop through the string and compare
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == ch) {
            count++; // Increment if character matches
        }
    }

    // Display result
    cout << "The character '" << ch << "' appears " << count << " times in the string." << endl;

    return 0; // Indicate successful execution
}

Console Output:

Enter a string: Hello World
Enter a character to search for: o
The character 'o' appears 2 times in the string.
Flow Control & Logic
String Character Counting C++ String Iteration Logic Standard String Input Methods Pattern Matching Basics in C++

Share this C++ Exercise

Help others learn string manipulation and loops in C++.

© C++ Programming Exercises. Master the art of performance coding.