w3resource

C++ String Exercises: Alternate the case of each letter in a string

C++ String: Exercise-42 with Solution

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>

using namespace std;
std::string test(std::string text) {
         std::string str;
         int ctr=0;
         for(char ch:text){
                  if(ctr%2==0)
                  str+=tolower(ch);
                  if(ctr%2!=0)
                  str+=toupper(ch);
                  if(ch==' ')
                  ctr++;
                  ctr++;
         }
         return str;
}int main()
{
         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:

Flowchart: Second occurrence of a string within another string.

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?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Ref: https://bit.ly/3niU71x