After reading a string (by whatever means), in addition to the toupper
function in ctype.h
, you can make case-coversions from lower-to-upper case (and from upper-to-lower) with simple bitwise operations.
Character Values
You will often hear the term 7-bit ASCII. This is due to the ASCII character set being represented by the first 7-bits in each character value. (the 8th-bit is always 0
for standard characters.) The 6th-bit is the case-bit. (for A-Za-z
) For A-Z
the case-bit is 0
and for a-z
it is 1
.
char | dec | hex | binary
-----+-------+--------+---------
A | 65 | 0x41 | 01000001
B | 66 | 0x42 | 01000010
C | 67 | 0x43 | 01000011
D | 68 | 0x44 | 01000100
...
a | 97 | 0x61 | 01100001
b | 98 | 0x62 | 01100010
c | 99 | 0x63 | 01100011
d | 100 | 0x64 | 01100100
To change from lower-case to upper-case, all that is required is checking to be sure you are operating on a-z
and then simply flipping the 6th-bit from 1
to 0
.
In your case, reading a string from stdin
and then changing any lower-case characters to upper-case can be done as follows:
#include <stdio.h>
enum { MAXC = 512 };
int main (void) {
char str[MAXC] = "";
char *p = str;
printf ("\n enter str: ");
if (!fgets (str, MAXC, stdin)) {
fprintf (stderr, "error: invalid input.\n");
return 1;
}
for (; *p; p++) /* for each character */
if ('a' <= *p && *p <= 'z') /* if lower-case */
*p ^= (1 << 5); /* set case bit upper */
printf (" uc-string: %s\n", str);
return 0;
}
Example Use/Output
$ ./bin/str2upper
enter str: This is A String with UPPPER and lower case.
uc-string: THIS IS A STRING WITH UPPPER AND LOWER CASE.
Look it over and let me know if you have any questions.