Convert String to Lowercase in C

C-Programs C-String-Programs

In this article, we are going to learn how to convert string to lowercase in C language. We will learn to do this by using multiple techniques like:

  • Convert string to lowercase string in C using tolower() Function
  • Convert string to lowercase string in C using Custom Function

1. Convert string to lowercase string in C using tolower() Function


The C standard library provides tolower() function to convert a C string to lower case. This function is defined in
header file.In this example, we are taking a char string and iterating over each character of this string.We are passing each character to tolower() function. The tolower() function accepts one argument of type unsigned char and returns its lowercase.let us see this in action in below code.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
    char *str = "WELCOME TO DEVENUM TUTORIALS";

    printf("UpperCase String is : %s\n", str);
    printf("LowerCase String is : ");
    for (size_t i = 0; i < strlen(str); ++i) 
    {
        printf("%c", tolower((unsigned char) str[i]));
    }
    printf("\n");

    return 0;
}

Output

UpperCase String is : WELCOME TO DEVENUM TUTORIALS
LowerCase String is : welcome to devenum tutorials

2. convert string to lowercase string in C Using Custom Function


In this example, we are making use of the same tolower() function as in the above example, but here we are doing this by doing some code refactoring. We have moved the logic to convert upper case string to lower case string in c language to a separate function. And also here we are creating a separate string in this function and then returning this converted string to the calling function. Let us see this in the below code example.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

char *ConverttoLowerCase(char *str, int len)
{
    char *charstr = malloc(sizeof(char) * len);

    for (int i = 0; i < len; ++i) 
    {
        charstr[i] = tolower((unsigned char)str[i]);
    }
    return charstr;
}

int main()
{
    char *str = "WELCOME TO DEVENEUM TUTORIAL.";

    printf("UpperCase String is : %s\n", str);
    int len = strlen(str);

    char *lower = ConverttoLowerCase(str, len);
    printf("LowerCase String is : %s", lower);
    
    free(lower);

    return 0;
}

Output

UpperCase String is : WELCOME TO DEVENEUM TUTORIAL.
LowerCase String is : welcome to deveneum tutorial.