String Manipulation Exercise (easy) Invert the capitalization of a string Parame
ID: 3778678 • Letter: S
Question
String Manipulation Exercise (easy) Invert the capitalization of a string Parameters: s - A null-terminated character string. Return Value: None. Result: The function should convert every lowercase character in the string s to uppercase, and every uppercase character to lowercase (and store the modified character back into s). Characters which are not uppercase or lowercase letters must be left as-is. For example, if the input string is "Csc111", this function would convert it to "cSC111". The standard library functions 'islower', 'isupper', 'tolower' and 'toupper' may be helpful for this. ================================================== */ void invert_case(char *s){ /* ... Your code here ... */ } /* invert_case */
Explanation / Answer
Please find the required program along with its output. Please see the comments against each line to understand the step.
#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>
using namespace std;
void invert_case(char *s){
int i=0;
while(s[i]!=NULL){ //iterate over all characters in the string
if(isalpha(s[i]) && isupper(s[i])){ //if the char is an aplhabet and also an upper case char
s[i] = tolower(s[i]); //convert to lower case
}else if(isalpha(s[i]) && islower(s[i])){ //if the char is an aplhabet and also an lower case char
s[i] = toupper(s[i]); //convert to upper case
}
i++;
}
}; /* invert_case */
int main()
{
char str[]="Test String. ";
invert_case(str);
cout << str << endl;
}
------------------------------
OUTPUT:
tEST sTRING.