String-Based Problems in C
String-Based Problems in C
Introduction
String-based problems help improve your understanding of character arrays and string manipulation in C.
👉 These are very important for coding interviews and real-world applications.
Why Learn String Problems?
- ✔ Improve logic building
- ✔ Master string handling
- ✔ Useful in interviews
- ✔ Strengthen problem-solving skills
1. Find String Length (Without strlen)
#include <stdio.h>
int main() {
char str[] = "Hello";
int i = 0;
while (str[i] != '\0') {
i++;
}
printf("Length = %d", i);
return 0;
}
Output
Length = 5
2. Reverse a String
#include <stdio.h>
int main() {
char str[] = "Hello";
int i, len = 0;
char temp;
while (str[len] != '\0')
len++;
for (i = 0; i < len / 2; i++) {
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
printf("Reversed = %s", str);
return 0;
}
Output
Reversed = olleH
3. Check Palindrome String
#include <stdio.h>
int main() {
char str[] = "madam";
int i, len = 0, flag = 1;
while (str[len] != '\0')
len++;
for (i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
flag = 0;
break;
}
}
if (flag)
printf("Palindrome");
else
printf("Not Palindrome");
return 0;
}
Output
Palindrome
4. Count Vowels and Consonants
#include <stdio.h>
int main() {
char str[] = "hello";
int i = 0, vowels = 0, consonants = 0;
while (str[i] != '\0') {
if (str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u')
vowels++;
else
consonants++;
i++;
}
printf("Vowels = %d\nConsonants = %d", vowels, consonants);
return 0;
}
Output
Vowels = 2
Consonants = 3
5. Convert to Uppercase
#include <stdio.h>
int main() {
char str[] = "hello";
int i = 0;
while (str[i] != '\0') {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32;
}
i++;
}
printf("Uppercase = %s", str);
return 0;
}
Output
Uppercase = HELLO
String Problems Table
| Program | Purpose |
|---|---|
| Length | Find string length |
| Reverse | Reverse string |
| Palindrome | Check palindrome |
| Vowels | Count vowels |
| Uppercase | Convert case |
Important Notes
-
Strings end with
\0 - Use loops for processing
- Be careful with indexing
Common Mistakes
- ❌ Missing null character
- ❌ Wrong loop conditions
- ❌ Case sensitivity issues
Pro Tips
- ✔ Practice string problems daily
- ✔ Avoid using built-in functions initially
- ✔ Understand ASCII values
- ✔ Try different variations
Conclusion
String-based problems are essential for mastering string manipulation in C. They improve logic and are important for interviews.
Practice regularly to become confident.
👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.
Comments
Post a Comment