Saved Bookmarks
| 1. |
Write a program to convert the characters of a string into the opposite case, that is, if a character is lowercase, convert it to upper case and vice versa. |
|
Answer» Input : Input : We scan each character of the string one by one. If the current character is in lowercase, we subtract 32 from the character and convert it to UPPERCASE. Similarly, if the current character is in uppercase, we add 32 to the character and convert it to lowercase. Code: #include <iostream>using namespace std; // Function to convert the characters of the string to its opposite casevoid changeCase(string& s){ int len = s.length(); for (int i = 0; i < len; i++) { if (s[i] >= 'a' && s[i] <= 'z') { s[i] = s[i] - 32;// Subtracting 32 from the character } else if (s[i] >= 'A' && s[i] <= 'Z') { s[i] = s[i] + 32;// Adding 32 to the character } }} int main(){ string s = "inTerVieWbiT"; cout << "Original String : " << s << "\n"; changeCase(s); cout << "Changed String : " << s << "\n"; RETURN 0;}Output: Original String : inTerVieWbiTChanged String : INtERvIEwBItExplanation : In the above code, we define a function named ‘changeCase’ which takes a reference of a string as a parameter. We iterate through each character of the string and change the character to its opposite case by either adding or subtracting 32. |
|