Practice essential string programs in C including anagram check, word count, vowel count, character frequency, remove duplicates, and more coding problems.
Mastering strings in C requires hands-on practice with real programming problems. This collection covers the most commonly asked string problems in technical interviews and university exams. Each program includes a clear approach, complete implementation, and sample output.
Program 1: Check if Two Strings are Anagrams
Two strings are anagrams if they contain the same characters with the same frequency, just rearranged (e.g., "listen" and "silent").
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int areAnagrams(const char *s1, const char *s2) {
int freq[26] = {0};
// Count characters in first string
for (int i = 0; s1[i] != '\0'; i++) {
if (isalpha(s1[i]))
freq[tolower(s1[i]) - 'a']++;
}
// Subtract characters from second string
for (int i = 0; s2[i] != '\0'; i++) {
if (isalpha(s2[i]))
freq[tolower(s2[i]) - 'a']--;
}
// If all counts are zero, strings are anagrams
for (int i = 0; i < 26; i++) {
if (freq[i] != 0) return 0;
}
return 1;
}
int main() {
printf("\"listen\" & \"silent\": %s\n",
areAnagrams("listen", "silent") ? "Anagram" : "Not anagram");
printf("\"hello\" & \"world\": %s\n",
areAnagrams("hello", "world") ? "Anagram" : "Not anagram");
printf("\"Triangle\" & \"Integral\": %s\n",
areAnagrams("Triangle", "Integral") ? "Anagram" : "Not anagram");
return 0;
}
"listen" & "silent": Anagram
"hello" & "world": Not anagram
"Triangle" & "Integral": Anagram
Program 2: Count Words in a String
#include <stdio.h>
#include <ctype.h>
int countWords(const char *str) {
int count = 0;
int inWord = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isspace(str[i])) {
inWord = 0;
} else if (!inWord) {
inWord = 1;
count++;
}
}
return count;
}
int main() {
char str1[] = "Hello World";
char str2[] = " The quick brown fox ";
char str3[] = "OneWord";
char str4[] = " ";
printf("\"%s\" → %d words\n", str1, countWords(str1));
printf("\"%s\" → %d words\n", str2, countWords(str2));
printf("\"%s\" → %d words\n", str3, countWords(str3));
printf("\"%s\" → %d words\n", str4, countWords(str4));
return 0;
}
"Hello World" → 2 words
" The quick brown fox " → 4 words
"OneWord" → 1 words
" " → 0 words
Program 3: Count Vowels and Consonants
#include <stdio.h>
#include <ctype.h>
void countVowelsConsonants(const char *str, int *vowels, int *consonants) {
*vowels = 0;
*consonants = 0;
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
(*vowels)++;
else
(*consonants)++;
}
}
}
int main() {
char str[] = "Hello World Programming";
int v, c;
countVowelsConsonants(str, &v, &c);
printf("String: \"%s\"\n", str);
printf("Vowels: %d\n", v);
printf("Consonants: %d\n", c);
return 0;
}
String: "Hello World Programming"
Vowels: 6
Consonants: 15
Program 4: Character Frequency Counter
#include <stdio.h>
#include <ctype.h>
void charFrequency(const char *str) {
int freq[26] = {0};
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
freq[tolower(str[i]) - 'a']++;
}
}
printf("Character frequencies:\n");
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
printf(" '%c': %d\n", 'a' + i, freq[i]);
}
}
}
int main() {
char str[] = "programming";
printf("String: \"%s\"\n\n", str);
charFrequency(str);
return 0;
}
String: "programming"
Character frequencies:
'a': 1
'g': 2
'i': 1
'm': 2
'n': 1
'o': 1
'p': 1
'r': 2
Program 5: Remove Duplicate Characters
#include <stdio.h>
#include <string.h>
void removeDuplicates(char str[]) {
int seen[256] = {0}; // Track all ASCII characters
int writePos = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (!seen[(unsigned char)str[i]]) {
seen[(unsigned char)str[i]] = 1;
str[writePos++] = str[i];
}
}
str[writePos] = '\0';
}
int main() {
char str[] = "programming";
printf("Before: %s\n", str);
removeDuplicates(str);
printf("After: %s\n", str);
return 0;
}
Before: programming
After: progamin
Program 6: Find First Non-Repeating Character
#include <stdio.h>
#include <string.h>
char firstNonRepeating(const char *str) {
int freq[256] = {0};
// Count frequencies
for (int i = 0; str[i] != '\0'; i++) {
freq[(unsigned char)str[i]]++;
}
// Find first with frequency 1
for (int i = 0; str[i] != '\0'; i++) {
if (freq[(unsigned char)str[i]] == 1) {
return str[i];
}
}
return '\0'; // All characters repeat
}
int main() {
char str1[] = "aabcbdce";
char str2[] = "aabbcc";
char result = firstNonRepeating(str1);
if (result)
printf("\"%s\" → first non-repeating: '%c'\n", str1, result);
result = firstNonRepeating(str2);
if (!result)
printf("\"%s\" → no non-repeating character\n", str2);
return 0;
}
"aabcbdce" → first non-repeating: 'd'
"aabbcc" → no non-repeating character
Program 7: Reverse Words in a String
#include <stdio.h>
#include <string.h>
void reverseSegment(char str[], int start, int end) {
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
void reverseWords(char str[]) {
int len = strlen(str);
// Step 1: Reverse entire string
reverseSegment(str, 0, len - 1);
// Step 2: Reverse each word
int start = 0;
for (int i = 0; i <= len; i++) {
if (str[i] == ' ' || str[i] == '\0') {
reverseSegment(str, start, i - 1);
start = i + 1;
}
}
}
int main() {
char str[] = "Hello World From C";
printf("Original: %s\n", str);
reverseWords(str);
printf("Reversed: %s\n", str);
return 0;
}
Original: Hello World From C
Reversed: C From World Hello
Program 8: Check if String is Pangram
A pangram contains every letter of the alphabet at least once (e.g., "The quick brown fox jumps over the lazy dog").
#include <stdio.h>
#include <ctype.h>
int isPangram(const char *str) {
int seen[26] = {0};
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
seen[tolower(str[i]) - 'a'] = 1;
}
}
for (int i = 0; i < 26; i++) {
if (!seen[i]) return 0;
}
return 1;
}
int main() {
char str1[] = "The quick brown fox jumps over the lazy dog";
char str2[] = "Hello World";
printf("\"%s\"\n → %s\n\n", str1, isPangram(str1) ? "Pangram" : "Not a pangram");
printf("\"%s\"\n → %s\n", str2, isPangram(str2) ? "Pangram" : "Not a pangram");
return 0;
}
"The quick brown fox jumps over the lazy dog"
→ Pangram
"Hello World"
→ Not a pangram
Program 9: Longest Word in a String
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void longestWord(const char *str) {
int maxLen = 0, maxStart = 0;
int currentLen = 0, currentStart = 0;
for (int i = 0; ; i++) {
if (str[i] == ' ' || str[i] == '\0') {
if (currentLen > maxLen) {
maxLen = currentLen;
maxStart = currentStart;
}
currentLen = 0;
currentStart = i + 1;
if (str[i] == '\0') break;
} else {
currentLen++;
}
}
printf("Longest word: ");
for (int i = maxStart; i < maxStart + maxLen; i++) {
putchar(str[i]);
}
printf(" (length: %d)\n", maxLen);
}
int main() {
char str[] = "I love programming in C language";
printf("String: \"%s\"\n", str);
longestWord(str);
return 0;
}
String: "I love programming in C language"
Longest word: programming (length: 11)
Program 10: String Permutations
#include <stdio.h>
#include <string.h>
void swap(char *a, char *b) {
char temp = *a;
*a = *b;
*b = temp;
}
void permutations(char str[], int left, int right, int *count) {
if (left == right) {
printf(" %s\n", str);
(*count)++;
return;
}
for (int i = left; i <= right; i++) {
swap(&str[left], &str[i]);
permutations(str, left + 1, right, count);
swap(&str[left], &str[i]); // Backtrack
}
}
int main() {
char str[] = "ABC";
int count = 0;
printf("Permutations of \"%s\":\n", str);
permutations(str, 0, strlen(str) - 1, &count);
printf("Total: %d permutations\n", count);
return 0;
}
Permutations of "ABC":
ABC
ACB
BAC
BCA
CBA
CAB
Total: 6 permutations
Interview Questions
Q1: How do you check if a string is a rotation of another string?
Concatenate the first string with itself. If the second string is a substring of this concatenation (using strstr), then it's a rotation. Example: "abcde" → "abcdeabcde" contains "cdeab" → rotation confirmed.
Q2: What's the most efficient way to count words in a string?
Use a state machine approach: track whether you're inside or outside a word. Each transition from "outside" to "inside" (non-space after space) increments the counter. This handles multiple spaces correctly in O(n) time.
Q3: How would you find the longest palindromic substring?
Expand around center: for each character (and each gap between characters), expand outward while characters match. Track the longest palindrome found. Time: O(n²), Space: O(1). Manacher's algorithm achieves O(n).
Q4: How do you remove all duplicates from a string while preserving order?
Use a boolean array of size 256 (for all ASCII characters) to track which characters have been seen. Write each character to the output position only if it hasn't been seen before. Time: O(n), Space: O(1).
Summary
- Anagram checking uses character frequency arrays — compare frequencies of both strings
- Word counting uses a state machine approach to handle multiple spaces correctly
- Frequency counting maps each character to an array index using ASCII values
- Reversing words: reverse entire string, then reverse each word individually
- Permutation generation uses recursive backtracking with swapping
- Most string problems can be solved in O(n) time using frequency arrays or two-pointer techniques