C Convert String to Lowercase and Uppercase
strlwr() and strupr() are not standard C functions. They work only in some compilers. The portable way is to use tolower() and toupper() from ctype.h on each character.
Convert to uppercase
#include <stdio.h>
#include <ctype.h>
int main(void) {
char s[] = "Learn C Programming";
for (int i = 0; s[i] != '\0'; i++) {
s[i] = toupper((unsigned char)s[i]);
}
printf("%s\n", s);
return 0;
}
Output:
Output of the above program is
LEARN C PROGRAMMING
Convert to lowercase
#include <stdio.h>
#include <ctype.h>
int main(void) {
char s[] = "Learn C Programming";
for (int i = 0; s[i] != '\0'; i++) {
s[i] = tolower((unsigned char)s[i]);
}
printf("%s\n", s);
return 0;
}
Output:
Output of the above program is
learn c programming
Reusable functions
#include <stdio.h>
#include <ctype.h>
void toUpperCase(char *s) {
for (; *s; s++) *s = toupper((unsigned char)*s);
}
void toLowerCase(char *s) {
for (; *s; s++) *s = tolower((unsigned char)*s);
}
int main(void) {
char a[] = "Hello World";
toUpperCase(a);
printf("%s\n", a);
toLowerCase(a);
printf("%s\n", a);
return 0;
}
Output:
Output of the above program is
HELLO WORLD
hello world
Other useful ctype functions
| Function | Checks |
|---|---|
isalpha(c) | Letter |
isdigit(c) | Digit 0 to 9 |
isalnum(c) | Letter or digit |
isspace(c) | Space, tab or new line |
isupper(c) / islower(c) | Capital or small letter |
Note:
toupper() and tolower() change only letters. Numbers and symbols stay the same.
Next: C Array of Strings.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |