Convert a String to Lowercase in C

To convert a string to lowercase in C, we can use functions like tolower() from ctype.h, or manually iterate through the string.

In this tutorial, we will explore multiple methods to convert a string to lowercase with examples.


Examples to Convert a String to Lowercase

1. Convert String to Lowercase Using tolower()

In this example, we will use the tolower() function from the ctype.h library. We will iterate through the string, convert each uppercase character to lowercase, and store the result.

main.c

</>
Copy
#include <stdio.h>
#include <ctype.h>

void toLowercase(char str[]) {
    for (int i = 0; str[i] != '\0'; i++) {
        str[i] = tolower(str[i]);
    }
}

int main() {
    char str[] = "Hello, World!";
    
    toLowercase(str);
    
    printf("Lowercase String: %s\n", str);
    
    return 0;
}

Explanation:

  1. We include ctype.h to use the tolower() function.
  2. We define a function toLowercase() that takes a character array str[].
  3. Inside the function, we loop through each character using for and check if it’s uppercase.
  4. The tolower() function converts uppercase letters to lowercase.
  5. We modify the string in place and print the result.

Output:

Lowercase String: hello, world!

2. Convert String to Lowercase Without Using Library Functions

If we do not want to use tolower() or strlwr(), we can manually convert characters by checking ASCII values.

main.c

</>
Copy
#include <stdio.h>

void manualToLowercase(char str[]) {
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] >= 'A' && str[i] <= 'Z') {
            str[i] = str[i] + 32; // Convert to lowercase
        }
    }
}

int main() {
    char str[] = "C LANGUAGE";

    manualToLowercase(str);
    
    printf("Lowercase String: %s\n", str);
    
    return 0;
}

Explanation:

  1. We declare a function manualToLowercase() that processes the string manually.
  2. We iterate through each character using a loop.
  3. We check if the character is uppercase (ASCII range 'A' to 'Z').
  4. We convert it to lowercase by adding 32 (ASCII difference between uppercase and lowercase).
  5. We modify the original string and print the result.

Output:

Lowercase String: c language

Conclusion

In this tutorial, we explored multiple ways to convert a string to lowercase in C:

  1. tolower() from ctype.h: Converts each character individually.
  2. Manual conversion: Iterating through the string and converting ASCII values.

tolower() is standard and widely available. The manual approach is useful when built-in functions are not available.