“I bought this guide a few days ago to prepare for my interview with Oracle. Many of the questions they asked me were from this guide. I found this book absolutely great!”
void ToUpper(char *str) { // do error checking. This impresses people if (!str) return;
for (int i = 0; str[i]; i++) { if (str[i] >= ‘a’ && str[i] <= ‘z’) str[i] = str[i] - 32; } }
this one is really straightforward once you realize that ‘A’ and ‘a’ are 32 apart. The ASCII table was designed so that major groups of characters were 32 apart, i.e., 32 control chars, then 32 upper case + numbers + symbols, then 32 lowercase + more symbols, …
Unfortunately, you can’t just toggle bit 32, since that would INVERT the case of the string. The problem says to convert a string to upper case.
Lowercase(c1) to uppercase(c2):
c2= c1 +’a'-’A';
Lower case to upper case is correctly like this:
if (islower(c))
c = c-’a'+’A’
Upper case to lower case is
if (isuuper(c))
c = c-’A'+’a’
Note. The condition tested is to prevent the translation of non-alphabetic characters.
Instead how about this way:
void ToUpper(char * S)
{
while (*S!=0)
{
*S=(*S>=’a’ && *S<=’z')?(*S-’a'+’A'):*S;
S++;
}
}
use the ascii set.
the lower case and upper case differ only on one bit..just toggle that bit.
Doesn’t matter which way the character is to be converted, just flip one bit.
ConvertChar( char *c )
{
*c = (*c) ^ (’A’ - ‘a’);
}
This should do it ( I have tested it):
char c;
c=c-(’a'-’A');
Try this
void ToUpper(char *str)
{
// do error checking. This impresses people
if (!str)
return;
for (int i = 0; str[i]; i++)
{
if (str[i] >= ‘a’ && str[i] <= ‘z’)
str[i] = str[i] - 32;
}
}
this one is really straightforward once you realize that ‘A’ and ‘a’ are 32 apart. The ASCII table was designed so that major groups of characters were 32 apart, i.e., 32 control chars, then 32 upper case + numbers + symbols, then 32 lowercase + more symbols, …
Unfortunately, you can’t just toggle bit 32, since that would INVERT the case of the string. The problem says to convert a string to upper case.
int main () {
char str[ ]={’s’,'t’,'r’,'i’,'n’,'g’,”};
char * ptr;
ptr=str;
while (*ptr!=”)
{
printf(”%c”,*ptr++);
}
ptr=str;
while (*ptr!=”)
{
*ptr=*ptr-0×20;
printf(”%c”,*ptr++);
}
return 0;
}
void ConvertChar( char *c )
{
*c = (*c) ^ (’a'-’A');
}
Leave an Answer/Comment