C Programming: Working with Strings
Unlike modern programming languages like Python or Java, C does not possess a dedicated "String" data type. Instead, C treats a string as a simple 1D array of characters.
Real-life example: Think of a freight train. The train does not exist as one solid object; it consists of individual boxcars linked together. Similarly, a C string links individual characters side-by-side in memory. To let the computer know the train has ended, C attaches a special "caboose" called the Null Terminator (\0).
1. Essential String Functions
Handling strings manually requires complex loops. To save time, C provides a built-in library called <string.h> that contains powerful functions to manipulate text.
- strlen(): You use this to find the exact length of a string. The compiler counts the characters until it hits the
\0terminator. It does not count the terminator itself. - strcpy(): You use this to copy the contents of one string directly into another. It overwrites whatever previously existed in the destination string.
- strcmp(): You use this to compare two strings lexicographically (alphabetical order). If the two strings match perfectly, the function returns a
0. If they differ, it returns a positive or negative number based on their ASCII differences. - strcat(): You use this to concatenate (link) two strings. The function takes the second string and seamlessly attaches it to the very end of the first string, effectively combining them.
2. Problem Solving Focus: String Algorithms
To master strings, you must understand how to navigate them character by character. Here are five classic string manipulation algorithms that you will encounter in coding interviews.
Problem 1: Reverse a String
We use the Two-Pointer technique. We place one pointer at the first character and one at the last valid character (right before the \0). We swap them and move inward.
#include <string.h>
int main() {
char str[] = "Programming";
int start = 0;
int end = strlen(str) - 1;
char temp;
while(start < end) {
// Swap the characters
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
printf("Reversed String: %s\n", str);
return 0;
}
Problem 2: Palindrome String Checker
A palindrome reads the exact same forwards and backwards (like "madam"). We use two pointers again. If at any point the left character does not match the right character, the word fails the test instantly.
#include <string.h>
int main() {
char str[] = "racecar";
int start = 0;
int end = strlen(str) - 1;
int isPalindrome = 1; // Assume true initially
while(start < end) {
if(str[start] != str[end]) {
isPalindrome = 0; // Mismatch found!
break;
}
start++;
end--;
}
if(isPalindrome)
printf("The string is a Palindrome.\n");
else
printf("The string is NOT a Palindrome.\n");
return 0;
}
Problem 3: Count Characters (Without strlen)
In interviews, companies frequently ask you to calculate the length of a string without using the built-in strlen() function. We solve this by looping through the array until we crash into the Null Terminator.
int main() {
char str[] = "Hello World";
int count = 0;
// Keep looping until we hit the \0 character
while(str[count] != '\0') {
count++;
}
printf("Total characters: %d\n", count);
return 0;
}
Problem 4: Remove Duplicates from a String
To eliminate duplicates cleanly, we use a Hash Array (or frequency tracker) of size 256 to cover all possible ASCII characters. As we read the string, we mark characters we have seen. If we encounter a marked character again, we simply skip it.
int main() {
char str[] = "programming";
int hash[256] = {0}; // Array to track seen characters
int currentIndex = 0;
for(int i = 0; str[i] != '\0'; i++) {
// If we have not seen this character yet
if(hash[(unsigned char)str[i]] == 0) {
hash[(unsigned char)str[i]] = 1; // Mark it as seen
str[currentIndex++] = str[i]; // Overwrite the string in place
}
}
// Terminate the new, shorter string
str[currentIndex] = '\0';
printf("String after removing duplicates: %s\n", str);
return 0;
}
Problem 5: Verify an Anagram
Two strings are anagrams if they use the exact same characters in the exact same quantities (like "listen" and "silent"). We build a single frequency array. We increment the count for every character in the first word, and decrement the count for every character in the second word. If the final array contains all zeros, they are a perfect match.
#include <string.h>
int main() {
char str1[] = "listen";
char str2[] = "silent";
int count[256] = {0};
int isAnagram = 1;
// If lengths differ, they physically cannot be anagrams
if(strlen(str1) != strlen(str2)) {
isAnagram = 0;
} else {
// Add frequencies from str1, subtract from str2
for(int i = 0; str1[i] != '\0'; i++) {
count[(unsigned char)str1[i]]++;
count[(unsigned char)str2[i]]--;
}
// Verify all buckets returned to exactly zero
for(int i = 0; i < 256; i++) {
if(count[i] != 0) {
isAnagram = 0;
break;
}
}
}
if(isAnagram)
printf("The strings ARE anagrams.\n");
else
printf("The strings are NOT anagrams.\n");
return 0;
}
Summary: Strings
- C does not have a dedicated string data type; it simply utilizes an array of characters.
- Every valid C string must end with a Null Terminator (
\0). - Programmers use the
<string.h>library to quickly copy, compare, and concatenate text without writing manual loops. - You can efficiently track and manipulate string data using an ASCII frequency array of size 256.
C Programming Interview Questions (FAQs)
Unlike other languages, C arrays do not automatically remember their own size. When you pass a string to a function like printf(), the computer has no idea where your text ends and where random memory garbage begins. The Null Terminator acts as a physical stop sign. The compiler reads characters one by one and instantly stops processing the moment it hits the \0.
When you write char arr[] = "Hello";, the compiler creates a fresh, mutable array in your local stack memory and copies the word "Hello" into it. You can modify any letter in this array. However, when you write char *str = "Hello";, the compiler creates a pointer that points to a "string literal" stored in the Read-Only Data Segment of the RAM. If you attempt to alter a letter in the char* version, the operating system instantly crashes your program with a Segmentation Fault.

Comments
Post a Comment