I was solving a very easy problem to convert a character in a string to lowercase, I obviously used tolower()
. However, I saw someone use this and it was an accepted solution.
Is this an alternative to tolower()
function in cpp? If so, why?
Reference to the problem: https://atcoder.jp/contests/abc126/tasks/abc126_a
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
// We want to convert "ABC" to "aBC"
string S = "ABC";
S[0] += 0x20;
// Returns "aBC"
cout << S << endl;
return 0;
}
This is simple ASCII manipulation. You see, the ASCII value to Uppercase A is 65 and lower case a is 97. If you add 32 (0x20 in hex) to 65, you get 97, the lower case a.
As all the alphabets in uppercase and all the alphabets in lowercase are laid out consecutively, you just need to add 32 or 0x20 to any uppercase alphabet and you'll get the lower case one.