I am trying to write a program that will take a sentence like "This is a TEST Sentence" and return "tHIS IS A test sENTENCE"
Using arrays and user defined functions in the solution
Use ASCII table. String operator[] function returns char, which has an associated ASCII integer value. Capital letters are all in the range 65-90(A-Z), and lower case letters are in range 97-122(a-z).
E.g.,
1 2 3 4 5 6 7 8 9 10 11 12 13
string s = "Hello World";
for(unsignedint i =0; i< s.length(); i++)
{
if(s[i] >=65 && s[i] <= 90)
cout << "This is capitalized!" << endl;
elseif(s[i] >=97 && s[i] <= 122)
cout << "This is lower case!" << endl;
//you can decide what to do if the char is not an alphabet by using 'else'.
}
The difference between lower case integers and capital letter integers is:
97 - 65 = 32
So we add 32 to upper case letters to convert to lower case letters and subtract 32 from lower case letters to convert to upper case letters. This can be done because char are implicitly converted to int. If you don't want to use implicit conversion, you have to add a few more lines of code.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string s = "Hello World";
for(unsignedint i =0; i< s.length(); i++)
{
if(s[i] >=65 && s[i] <= 90)
s[i] = s[i] + 32;
elseif(s[i] >=97 && s[i] <= 122)
s[i] = s[i] - 32;
//you can decide what to do if the char is not an alphabet by using 'else'.
}
cout << s;
return 0;
}
You will have to find a way to implement this using arrays and user defined functions. Notice that a string has the array '[]' operator to access elements.