String manipulation is an essential part of programming. In this post, you’ll learn how to write a C function to convert all lowercase characters in a string to their uppercase equivalents using basic character operations.
Problem Statement
Write a function that:
- Accepts a character string as an argument.
- Scans each character in the string.
- Converts all lowercase letters (
a-z
) to their uppercase equivalents (A-Z
).
Concept Behind the Logic
In C, characters are stored using ASCII values:
- The ASCII value of
'a'
is 97 and'A'
is 65. - So the difference between lowercase and uppercase is 32.
You can convert a lowercase letter to uppercase by subtracting 32 from its ASCII value.
C Function to Convert Lowercase to Uppercase
#include <stdio.h>
void toUpperCase(char *str) {
int i = 0;
while (str[i] != '\0') {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32;
}
i++;
}
}
int main() {
char text[100];
printf("Enter a string: ");
fgets(text, sizeof(text), stdin);
toUpperCase(text);
printf("Uppercase string: %s", text);
return 0;
}
Sample Output
Enter a string: Hello World
Uppercase string: HELLO WORLD
Explanation
- The function
toUpperCase()
takes a character pointer. - It iterates through each character in the string.
- If the character is between
'a'
and'z'
, it is converted by subtracting 32. - The updated string is then printed in
main()
.
Key Points
- You don’t need any special library to convert characters manually.
- For more robust code, use
toupper()
from<ctype.h>
, but in this example we use ASCII arithmetic for clarity.
Final Thoughts
This is a classic string manipulation task in C. Practicing this helps in:
- Understanding pointer usage in functions.
- Learning ASCII-based operations.
- Strengthening your grasp on string handling.
Now go ahead, tweak the function, and try writing a lowercase-to-uppercase converter for user input with more validations!