C Program To Convert String In Upper Case And Lower Case
In this article, you will learn how to convert strings to uppercase and lowercase in C using standard library functions and manual character manipulation. We will explore different methods, provide practical code examples, and explain each step in detail.
Problem Statement
Strings are fundamental data types in programming, and often there's a need to standardize their case for comparison, display, or storage. For instance, "apple", "Apple", and "APPLE" might represent the same entity but differ in case, leading to issues in search functions or data processing. The problem is to efficiently transform all alphabetic characters within a given string to either their uppercase or lowercase equivalents.
Example
Consider the input string: "Hello, World! 123"
- Uppercase Conversion Output: "HELLO, WORLD! 123"
- Lowercase Conversion Output: "hello, world! 123"
Background & Knowledge Prerequisites
To understand this article, readers should have a basic grasp of:
- C Language Fundamentals: Variables, data types, loops (for, while).
- Character Arrays (Strings): How strings are represented in C as null-terminated character arrays.
- Pointers: Basic understanding of pointers, especially when working with character arrays.
- Standard Input/Output: Using
printfandscanf(orfgets). - Standard Library Functions: Familiarity with basic functions from
and.
Essential includes for the examples will be:
-
#includefor input/output operations. -
#includefor string manipulation functions (likestrlen). -
#includefor character classification and conversion functions.
Use Cases or Case Studies
String case conversion is vital in various scenarios:
- Data Normalization: Ensuring consistency in data entry, like converting all user-entered names to proper case or all product IDs to uppercase for unique identification.
- Case-Insensitive Comparisons: Before comparing two strings, converting both to a uniform case (either all uppercase or all lowercase) allows for case-insensitive matching.
- User Interface Display: Formatting text for display, such as title casing for headings or all caps for warnings.
- Parsing and Validation: When processing commands or user input, converting to a known case simplifies parsing rules.
- Database Queries: Many database systems perform case-sensitive searches by default, so normalizing case before querying can improve result accuracy.
Solution Approaches
We will explore two primary approaches for converting string cases in C: using the ctype.h library functions and performing manual ASCII-based conversion.
Approach 1: Using toupper() and tolower() functions
These functions from the library provide a robust and portable way to convert characters.
Convert to Uppercase using toupper()
Summary: Iterates through the string, converting each character to its uppercase equivalent using toupper().
// String to Uppercase using toupper()
#include <stdio.h>
#include <string.h> // For strlen
#include <ctype.h> // For toupper
void toUpperCase(char *str) {
// Step 1: Iterate through the string until the null terminator is found.
for (int i = 0; str[i] != '\\0'; i++) {
// Step 2: Use toupper() to convert the character to uppercase.
// toupper() returns the uppercase equivalent if it's a lowercase letter,
// otherwise, it returns the character itself unchanged.
str[i] = toupper((unsigned char)str[i]);
}
}
int main() {
char myString[] = "Hello, World! 123";
printf("Original string: %s\\n", myString);
// Step 3: Call the toUpperCase function.
toUpperCase(myString);
printf("Uppercase string: %s\\n", myString);
return 0;
}
Sample Output:
Original string: Hello, World! 123
Uppercase string: HELLO, WORLD! 123
Stepwise Explanation:
- The
toUpperCasefunction takes a character pointerstr(representing the string) as input. - It iterates through the string using a
forloop, stopping when it encounters the null terminator (\0). - Inside the loop,
toupper((unsigned char)str[i])is called for each character.
-
toupper()is designed to convert a lowercase letter to its uppercase equivalent. Non-alphabetic characters or already uppercase letters are returned unchanged. - Casting to
(unsigned char)is crucial to prevent undefined behavior with negativecharvalues (which can occur ifcharis signed and a character has a value > 127).
- The result of
toupper()is then assigned back tostr[i], modifying the string in place. - In
main, an example string is declared, printed, converted, and then printed again.
Convert to Lowercase using tolower()
Summary: Iterates through the string, converting each character to its lowercase equivalent using tolower().
// String to Lowercase using tolower()
#include <stdio.h>
#include <string.h> // For strlen
#include <ctype.h> // For tolower
void toLowerCase(char *str) {
// Step 1: Iterate through the string until the null terminator is found.
for (int i = 0; str[i] != '\\0'; i++) {
// Step 2: Use tolower() to convert the character to lowercase.
// tolower() returns the lowercase equivalent if it's an uppercase letter,
// otherwise, it returns the character itself unchanged.
str[i] = tolower((unsigned char)str[i]);
}
}
int main() {
char myString[] = "HELLO, WORLD! 123";
printf("Original string: %s\\n", myString);
// Step 3: Call the toLowerCase function.
toLowerCase(myString);
printf("Lowercase string: %s\\n", myString);
return 0;
}
Sample Output:
Original string: HELLO, WORLD! 123
Lowercase string: hello, world! 123
Stepwise Explanation:
- The
toLowerCasefunction works similarly totoUpperCase. - It iterates through the string using a
forloop. tolower((unsigned char)str[i])is called for each character.
-
tolower()converts an uppercase letter to its lowercase equivalent, leaving other characters unchanged. - Again, casting to
(unsigned char)handles potentialchartype issues.
- The converted character is stored back into
str[i]. - The
mainfunction demonstrates its use with an example string.
Approach 2: Manual Conversion using ASCII Values
This approach relies on the fact that uppercase and lowercase English alphabets have a consistent difference in their ASCII values.
Convert to Uppercase Manually
Summary: Iterates through the string and subtracts 32 from the ASCII value of each lowercase letter to convert it to uppercase.
// String to Uppercase Manually
#include <stdio.h>
#include <string.h> // For strlen
void toUpperCaseManual(char *str) {
// Step 1: Iterate through the string until the null terminator is found.
for (int i = 0; str[i] != '\\0'; i++) {
// Step 2: Check if the current character is a lowercase English letter.
// ASCII values: 'a' is 97, 'z' is 122.
if (str[i] >= 'a' && str[i] <= 'z') {
// Step 3: Convert to uppercase by subtracting 32 from its ASCII value.
// (e.g., 'a' (97) - 32 = 'A' (65))
str[i] = str[i] - 32;
}
}
}
int main() {
char myString[] = "Hello, World! 123";
printf("Original string: %s\\n", myString);
// Step 4: Call the toUpperCaseManual function.
toUpperCaseManual(myString);
printf("Uppercase string: %s\\n", myString);
return 0;
}
Sample Output:
Original string: Hello, World! 123
Uppercase string: HELLO, WORLD! 123
Stepwise Explanation:
- The
toUpperCaseManualfunction iterates through the input string. - For each character, it checks if it falls within the ASCII range of lowercase English letters (
'a'to'z'). - If it is a lowercase letter,
32is subtracted from its ASCII value. This converts it to its corresponding uppercase character (e.g., 'a' (ASCII 97) becomes 'A' (ASCII 65)). - Other characters (uppercase letters, numbers, symbols) are left unchanged.
- The
mainfunction demonstrates the use with an example.
Convert to Lowercase Manually
Summary: Iterates through the string and adds 32 to the ASCII value of each uppercase letter to convert it to lowercase.
// String to Lowercase Manually
#include <stdio.h>
#include <string.h> // For strlen
void toLowerCaseManual(char *str) {
// Step 1: Iterate through the string until the null terminator is found.
for (int i = 0; str[i] != '\\0'; i++) {
// Step 2: Check if the current character is an uppercase English letter.
// ASCII values: 'A' is 65, 'Z' is 90.
if (str[i] >= 'A' && str[i] <= 'Z') {
// Step 3: Convert to lowercase by adding 32 to its ASCII value.
// (e.g., 'A' (65) + 32 = 'a' (97))
str[i] = str[i] + 32;
}
}
}
int main() {
char myString[] = "HELLO, WORLD! 123";
printf("Original string: %s\\n", myString);
// Step 4: Call the toLowerCaseManual function.
toLowerCaseManual(myString);
printf("Lowercase string: %s\\n", myString);
return 0;
}
Sample Output:
Original string: HELLO, WORLD! 123
Lowercase string: hello, world! 123
Stepwise Explanation:
- The
toLowerCaseManualfunction iterates through the input string. - It checks if the current character is an uppercase English letter (
'A'to'Z'). - If it is an uppercase letter,
32is added to its ASCII value, converting it to its lowercase counterpart (e.g., 'A' (ASCII 65) becomes 'a' (ASCII 97)). - Other characters remain untouched.
- The
mainfunction showcases this conversion.
Conclusion
Converting string case in C can be achieved effectively using both standard library functions and manual ASCII manipulation. The toupper() and tolower() functions from offer a robust, portable, and generally recommended approach due to their proper handling of character sets beyond basic ASCII. Manual ASCII conversion provides a deeper understanding of character encoding but is typically limited to English alphabets and requires careful boundary checks.
Summary
-
toupper()andtolower()(from): - Recommended for portability and correct behavior across different character sets.
- Convert individual characters to uppercase or lowercase.
- Require casting the
charargument to(unsigned char)to prevent potential issues with negativecharvalues. - Do not modify non-alphabetic characters or characters already in the target case.
- Manual ASCII Conversion:
- Involves adding or subtracting 32 from a character's ASCII value.
- Suitable primarily for English alphabets where 'a'-'z' and 'A'-'Z' have a consistent ASCII offset.
- Requires explicit checks (
if (str[i] >= 'a' && str[i] <= 'z')) to ensure only relevant characters are modified. - Offers insight into character encoding but is less flexible for international characters than
ctype.hfunctions. - In-Place Modification: Both approaches demonstrate modifying the string directly by assigning the converted character back to its position in the array.