Case Conversion in Strings
Learn about converting strings to uppercase and lowercase.
String conversion to lowercase
Let’s make a strLower()
function in which we need to convert uppercase alphabets to lowercase by adding the ASCII value. For example, if the ASCII value of A
is 65
, simply add 32
to convert it into lowercase. If you don’t remember the ASCII value, you can add the following in the alphabet:
alphabet+'a'-'A'
#include <iostream>#include <string.h>using namespace std;void strLower(char S[ ]){for(int si=0; S[si]!='\0'; si++){if(S[si]>='A' && S[si]<='Z'){S[si]+=32; // the ascii value of 'a' 97 i.e. 65(ascii value of 'A')+32 and so on}}}int main(){char S[ ] = "THIS is A WORLD OF C++";cout << "Before lowering: "<<S<<endl;strLower(S);cout << "After lowering: "<<S<<endl;return 0;}
Here are two challenges for you.
Exercise 1: String conversion to uppercase
Write the strUpper()
function solution.
Sample input
This is A World of C++
Sample output
THIS IS A WORLD OF C++
#include <iostream> #include <string.h> using namespace std; void strUpper(char S[ ]) { //write your code here } int main() { char S[ ] = "This is A WORLD of C++"; cout << "Before strUpper function:"<<S<<endl; strUpper(S); cout << "After strUpper function: "<<S<<endl; return 0; }
The strUpper() function
Exercise 2: Special to lowercase conversion
Write the strLowerSpecial()
function, which lowers the case of all the characters but not the start of the word.
Sample input
THIS IS PAKISTAN
Sample output
This Is Pakistan
#include <iostream> #include <cstring> using namespace std; void strLowerSpecial(char S[ ]) { //write your code here } int main() { char S[ ] = "THIS IS PAKISTAN"; cout << "Before lowering: "<<S<<endl; strLowerSpecial(S); cout << "After lowering: "<<S<<endl; return 0; }
The strLowerSpecial() function