-
quick question
Is there any functions in the stdlib to convert strings to lower or uppercase ??
I know there is tolower() and toupper() for char.
Is it best to just use a char array instead of strings and work through the array in a for loop ??
Does everyone out there use String or char[index] ??
Thanks
-
AFAIK you'll have to loop through the strings. It's pretty much the same process for character arrays or C++ strings -
Code:
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
using namespace std;
void mytoupper(char& c)
{
c-=32;
}
int main()
{
string name1 = "zen";
char name2 []= "zen";
//c string
for_each(&name2[0],&name2[strlen(name2)],mytoupper);
//c++ string
for_each(name1.begin(),name1.end(),mytoupper);
cout << name1 << endl << name2;
return 0;
}
You could use normal for loops and the standard library toupper (I was bored).
-
that wont work if you pass in "ZEN" or "Zen" or anything with an uppercase char in it... you need to this:
void MyToUpper(char& c)
{
c &= ~0x20;
}
void MyToLower(char& c)
{
c |= 0x20;
}
This will make sure that it works no matter what case is passed in
U.
-
OK I know Uraldor' code works a treat, but I don't understand how it works ?
Can anyone explain how the code works ?
Ta
-
In ASCII the difference between the higher and lower case characters is that the lower case characters have the fifth bit set and the higher case don't. 0x20 (32 = 2^5) is the fifth bit, so Uraldors function removes that bit in toupper and sets it in tolower, using 0x20 and ~0x20 (0xDF) as masks.
-
Some compilers have strupr and strlwr in <string.h> or <cstring>. It may not be part of the standard though.
char str[31];
cout << "Enter a string:";
cin >> str;
strupr(str);
cout << "str:" << str << endl;
-
void AllUpperString(char* input)
{
for(i = 0; i < strlen(input); i++)
{
input[i] = toupper(input[i]);
}
}