📌 Convert String to Lowercase in C Program
In C programming, we can convert a string to lowercase using loops and built-in functions.
🔹 Methods to Convert String to Lowercase
✔ Method 1: Using strlwr() (not standard in some compilers like GCC)
✔ Method 2: Using tolower() function from ctype.h
✔ Method 3: Using ASCII value transformation🔹 Method 1: Convert to Lowercase using strlwr()
✔ strlwr() is a built-in function in Turbo C / MSVC but not available in GCC.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
// Input string
printf("Enter a string: ");
gets(str); // Unsafe, use fgets in real projects
// Convert to lowercase
strlwr(str);
// Output result
printf("Lowercase String: %s\n", str);
return 0;
}
🚀 Sample Output
Enter a string: Hello World
Lowercase String: hello world
✔ Simple and efficient, but not available in GCC.
🔹 Method 2: Convert to Lowercase using tolower()
✔ tolower() converts each character to lowercase.
✔ Works in all compilers (Standard C function).#include <stdio.h>
#include <ctype.h> // Required for tolower()
int main() {
char str[100];
int i;
// Input string
printf("Enter a string: ");
gets(str); // Use fgets in real projects
// Convert each character to lowercase
for (i = 0; str[i] != '\0'; i++) {
str[i] = tolower(str[i]);
}
// Output result
printf("Lowercase String: %s\n", str);
return 0;
}
🚀 Sample Output
Enter a string: Welcome123@C
Lowercase String: welcome123@c
✔ Handles numbers and special characters correctly.
✔ Portable and works in all C compilers.🔹 Method 3: Convert to Lowercase using ASCII Values
✔ A-Z (65-90), a-z (97-122) in ASCII.
✔ If a character is uppercase (A-Z), add 32 to convert it to lowercase.#include <stdio.h>
int main() {
char str[100];
int i;
// Input string
printf("Enter a string: ");
gets(str);
// Convert to lowercase manually using ASCII values
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] + 32; // Convert uppercase to lowercase
}
}
// Output result
printf("Lowercase String: %s\n", str);
return 0;
}
🚀 Sample Output
Enter a string: HELLO C PROGRAMMING
Lowercase String: hello c programming
✔ Works without ctype.h
✔ Manually converts characters🔹 Summary Table
🎯 Conclusion
✔ Use tolower() for portability.
✔ Use ASCII transformation if you want manual control.
✔ Avoid strlwr() in GCC, as it's not standard.🚀 String manipulation is essential for C programming! 🔥
0 Comments