Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Change every letter in a given string with the letter following it in the alphabet

C++ String: Exercise-2 with Solution

Write a C++ program to change every letter in a given string with the letter following it in the alphabet (ie. a becomes b, p becomes q, z becomes a).

Pictorial Presentation:

C++ Exercises: Change every letter in a given string with the letter following it in the alphabet

Sample Solution:

C++ Code :

#include <iostream>
#include <string>
using namespace std;

string change_letter(string str) {

	int char_code;
	
	for (int x = 0; x < str.length(); x++)
	{
		char_code = int(str[x]);

		if (char_code == 122)
		{
			str[x] = char(97);
		}
		else if (char_code == 90)
		{
			str[x] = char(65);
		}
		else if (char_code >= 65 && char_code <= 90 || char_code >= 97 && char_code <= 122)
		{
			str[x] = char(char_code + 1);
		}
	
	}

	return str;
}

int main() 
{
	cout << "Original string: w3resource"; 
	cout << "\nNew string: " << change_letter("w3resource");
	cout << "\n\nOriginal string: Python"; 
	cout << "\nNew string: " << change_letter("Python");
	return 0;
}

Sample Output:

Original string: w3resource
New string: x3sftpvsdf

Original string: Python
New string: Qzuipo

Flowchart:

Flowchart: Change every letter in a given string with the letter following it in the alphabet.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to reverse a given string.
Next: Write a C++ program to capitalize the first letter of each word of a given string. Words must be separated by only one space.

What is the difficulty level of this exercise?