Sometimes we may need to convert a string to either lowercase or uppercase depending on the program requirement. We have a set of functions in C Library to convert a string to either lowercase or uppercase.
Note that, these functions are not standard library functions, and you may or may not see these functions in your version of C.
Convert a string to lowercase
By using strlwr()
function in C, we can convert a string to lowercase; which means all of the string characters are in lowercase. The syntax of the function looks like below;
char *strlwr(char *str);
It takes a string as an argument and converts the string to a lowercase string. Observe that, it will convert the original string to a lowercase string; and returns the address of the string.
Convert a string to uppercase
C provides strupr()
function to convert a string to uppercase. The syntax of the function looks like below;
char *strupr(char *str);
This function takes a single argument, string as an argument, converts the string to uppercase, and returns the address of the string. Observe that, this function converts the original string to uppercase.
Here is a working example where you can see the string is converted to lowercase and uppercase.
#include <stdio.h> #include <string.h> int main() { const char str[] = "Hello World!"; printf("Lowercase: %s\n", strlwr(str)); printf("Uppercase: %s\n", strupr(str)); return 0; }
Our own functions to convert strings to either lowercase or uppercase
As mentioned above, strlwr()
& strupr()
functions are non-standard C library functions and if you do not find these functions in your version of C, you can simply write your own functions to convert a string to lowercase or uppercase with the help of tolower()
& toupper()
character conversion functions.
tolower()
function is to convert a character to lowercase and toupper()
function is used to convert a character to uppercase. By using these functions, now we are going to implement our own versions of strlwr()
and strupr()
functions to convert a string to either lowercase or uppercase.
Here is the working code;
char* str2lower(char *str) { if (str == 0) return (char*)0; int len = strlen(str); for (int i = 0; i < len; i++) { str[i] = tolower(str[i]); } return str; } char* str2upper(char* str) { if (str == 0) return (char*)0; int len = strlen(str); for (int i = 0; i < len; i++) { str[i] = toupper(str[i]); } return str; }
//Malin