# How to convert a C-string to upper/lowercase

H

Often, I find myself in situations where I need to convert a string to either uppercase or lowercase. A nifty trick I often employ is leveraging the ASCII code, where each character corresponds to a specific number. The beauty lies in the fact that the uppercase letters (A-Z) and lowercase letters (a-z) are neatly organized into continuous ranges of ASCII values. For instance, a quick visit to http://www.asciitable.com/ reveals that A-Z resides between 0x41 and 0x5A, while the lowercase letters a-z span from 0x61 to 0x7A.

Considering this insight and the fundamental principle in the C language that, essentially, everything is a number in memory, we can devise a straightforward and comprehensive solution for string case conversion. By tapping into the inherent numerical nature of characters, we unlock a simple and efficient method to handle these conversions effortlessly. This elegant approach not only showcases the interconnectedness of programming concepts but also underscores the power of understanding the underlying principles at play.

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

typedef enum
{
CONVERT_TO_UPPERCASE = 0x00,
CONVERT_TO_LOWERCASE = 0x01
} convert_to;

void convert_string_case(convert_to to, char* input_string)
{
if (input_string == NULL)
return;

size_t str_length = strlen(input_string);

if (str_length < 2)
return;

for (size_t i = 0; i < str_length; i++)
{
if (to == CONVERT_TO_LOWERCASE && (input_string[i] >= 'A' && input_string[i] <= 'Z'))
input_string[i] += 0x20;
else if (to == CONVERT_TO_UPPERCASE && (input_string[i] >= 'a' && input_string[i] <= 'z'))
input_string[i] -= 0x20;
}
}

// Example for Testing the Function
int main()
{
char test_string[] = "Hello There!!!";
convert_string_case(CONVERT_TO_LOWERCASE, test_string);
return 0;
}``````
Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.