How to convert a C-string to upper/lowercase

H

Sometimes I needed to convert a string to upper or lowercase.

A quick trick that we are going to use is the fact that each character has a corresponding number in ASCII code and that the letters A-Z and a-z are separated in two groups of continuous corresponding numbers. For example if we look at http://www.asciitable.com/ we will see that A-Z is between 0x41 and 0x5A and the group of letters a-z starts at 0x61 until 0x7A.  

Having the previous in mind, as well as that in C language (basically in memory) everything is actually a number we could have a simple and complete solution for the conversion. 

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

typedef enum
{
    UPPERCASE = 0x00,
    LOWERCASE = 0x01
}convert_to_e;

static void str_case_converter(convert_to_e to, char* arg)
{
    if (arg == NULL)
        return;

    if (strlen(arg) == 0 || strlen(arg) == 1)
        return;

    for (int i = 0; i < strlen(arg); i++)
    {
        if (to == LOWERCASE && (arg[i] >= 'A' && arg[i] <= 'Z'))
            arg[i] = arg[i] + 0x20;
        else if (to == UPPERCASE && (arg[i] >= 'a' && arg[i] <= 'z'))
            arg[i] = arg[i] - 0x20;
    }
}

/// Example for Testing the function

int main()
{
    char test0[] = "Hello There!!!";
    str_case_converter(LOWERCASE,test0);
    
    return 0;
}

1 comment

Categories

Tags