C++ String Exercises: Alternate the case of each letter in a string
42. Alternate the Case of Each Letter in a String
Write a C++ program that alternates the case of each letter in a given string of letters.
Pattern: First lowercase letter then uppercase letter and so on.
Test Data:
("JavaScript") -> "jAvAsCrIpT"
("Python") -> "pYtHoN"
("C++") -> "c++"
Sample Solution:
C++ Code:
#include <bits/stdc++.h> // Include all standard libraries
using namespace std; // Using the standard namespace
// Function to alternate the case of each letter in a given string
std::string test(std::string text) {
std::string str; // Initialize an empty string to store the modified text
int ctr = 0; // Initialize a counter variable
// Loop through each character in the input text
for (char ch : text) {
if (ctr % 2 == 0) // If the counter is even
str += tolower(ch); // Convert the character to lowercase and append to the result string
if (ctr % 2 != 0) // If the counter is odd
str += toupper(ch); // Convert the character to uppercase and append to the result string
if (ch == ' ') // If the character is a space
ctr++; // Increment the counter
ctr++; // Increment the counter after every character
}
return str; // Return the modified string
}
int main() {
// Test cases
string text = "JavaScript";
cout << "Original String: " << text;
cout << "\nAlternate the case of each letter in the said string: " << test(text);
text = "Python";
cout << "\n\nOriginal String: " << text;
cout << "\nAlternate the case of each letter in the said string: " << test(text);
text = "C++";
cout << "\n\nOriginal String: " << text;
cout << "\nAlternate the case of each letter in the said string: " << test(text);
}
Sample Output:
Original String: JavaScript Alternate the case of each letter in the said string: jAvAsCrIpT Original String: Python Alternate the case of each letter in the said string: pYtHoN Original String: C++ Alternate the case of each letter in the said string: c++
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to iterate over a string and alternate the case of each letter starting with lowercase for the first letter.
- Write a C++ program that reads a string and toggles each alphabet’s case so that even-indexed letters become lowercase and odd-indexed become uppercase.
- Write a C++ program to process a string and output a new string with alternating cases, using ASCII arithmetic to change letter cases.
- Write a C++ program that takes an input string and produces an output where the case of letters alternates between lower and upper, ignoring non-alphabet characters.
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous C++ Exercise: Second occurrence of a string within another string.
What is the difficulty level of this exercise?