Convert C string to upper case

C: convert string to lowercase and uppercase

Introduction

Today we will see how to convert a string in C to uppercase. We will also see how to convert a string to lowercase. That is, to convert something like “Hello World” to “hello world”. Or something like “Good night” to “GOOD NIGHT”.

For this we will use some functions that the standard library has: tolower and toupper.

ctype.h library in C

To use toupper and tolower in C we will need to include the library that defines it. We simply include it with #include:

#include <ctype.h>

With this we can use toupper and tolower in C to convert strings.

Convert C string to uppercase

There is no direct way to convert a string to upper case; but there is a way to convert a char to a capital letter.

Remember that strings are only arrays of characters; so we can go through them and capitalize each of its elements. Then let’s see this program that defines a string and then converts it to uppercase to print it later:

/*
	Convert C string to uppercase

	@author parzibyte
*/
#include <stdio.h>
#include <ctype.h>

int main(int argc, char const *argv[])
{
	char my_string[] = "Hello world! this is a simple string. parzibyte.me";
	printf("Original string: %s\n", my_string);

	// Convert each char
	// using toupper
	for (int index = 0; my_string[index] != '\0'; ++index){
		my_string[index] = toupper(my_string[index]);
	}
	printf("After convert: %s\n", my_string);
	return 0;
}

First we define a string. We print it to show it in its original state. Then we do a for loop where we increase the index from 0 until we reach the termination character \0

For each element in the array we convert the capital letter using toupper function that comes when we include ctype.h

The execution of the program is as follows:

Convert C string to upper case
Convert C string to upper case

Convert string to lowercase in C

This is almost the same as above, but now we use tolower. The same code above, but to convert a string to lowercase, looks like this:

/*
	Convert C string to lowercase

	@author parzibyte
*/
#include <stdio.h>
#include <ctype.h>

int main(int argc, char const *argv[])
{
	char my_string[] = "Hello world! this is a simple string. parzibyte.me";
	printf("Original string: %s\n", my_string);

	// Convert each char
	// using tolower
	for (int index = 0; my_string[index] != '\0'; ++index){
		my_string[index] = tolower(my_string[index]);
	}
	printf("After convert: %s\n", my_string);
	return 0;
}

What we do is go through the string and turn each character into its lowercase representation.

Conclusion

This is how we can convert a string to uppercase or lowercase using the C language.


I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation

Leave a Comment

Your email address will not be published. Required fields are marked *