In this article, we are going to learn how to convert string to an upper case string in the C language. We will learn to do this by using multiple techniques like:
- Convert string to Uppercase string in C Using toupper() Function
- Convert string to Uppercase string in C Using Custom Function
1. Convert string to uppercase string in C Using toupper() Function
The C standard library provides toupper() function to convert a C string to upper case. This function is defined in
the 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 toupper() function. The toupper() function accepts one argument of type unsigned char and returns its uppercase. let us see this in action in the below code.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char *str = "welcome to devenum tutorials";
printf("LowerCase String is : %s\n", str);
printf("UpperCase String is : ");
for (size_t i = 0; i < strlen(str); ++i)
{
printf("%c", toupper((unsigned char) str[i]));
}
printf("\n");
return 0;
}
Output
LowerCase String is : welcome to devenum tutorials
UpperCase String is : WELCOME TO DEVENUM TUTORIALS
2. Convert string to uppercase string in C Using Custom Function
In this example, we are making use of the same toupper() function as in the above example, but here we are doing this by doing some code refactoring. We have moved the logic to convert lower case string to upper 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 *ConverttoUpperCase(char *str, int len)
{
char *charstr = malloc(sizeof(char) * len);
for (int i = 0; i < len; ++i)
{
charstr[i] = toupper((unsigned char)str[i]);
}
return charstr;
}
int main()
{
char *str = "welcome to deveneum tutorial";
printf("LowerCase String is : %s\n", str);
int len = strlen(str);
char *lower = ConverttoUpperCase(str, len);
printf("UpperCase String is : %s", lower);
free(lower);
return 0;
}
Output
LowerCase String is : welcome to deveneum tutorial
UpperCase String is : WELCOME TO DEVENEUM TUTORIAL