String Examples (C Programming)
Learn String Examples (C Programming) step by step with clear examples and exercises.
Title: String Examples (C Programming)
Why This Matters
In C programming, strings are essential for handling text data. They are used extensively in real-world applications, from creating simple text-based programs to developing complex software systems. Understanding string examples can help you solve problems efficiently and prepare for coding interviews or exams.
Prerequisites
To fully grasp the concepts covered in this lesson, you should have a good understanding of:
- C basics (variables, data types, operators)
- Control structures (if-else statements, loops)
- Arrays and pointers
- Basic file I/O operations
- Functions and function pointers
- Standard library functions (string.h, math.h, ctype.h)
Core Concept
What is a String in C?
A string in C is an array of characters that ends with a null character (\0). This null character signifies the end of the string and helps the program distinguish between individual strings and single characters. In C, strings are treated as arrays of characters, and you can manipulate them using various functions from the string.h library.
String Literals
String literals in C are enclosed in double quotes (""). For example:
char str1[] = "Hello, World!";
Here, str1 is an array of characters that stores the string "Hello, World!". The compiler automatically appends a null character (\0) at the end of the string.
String Length
To find the length of a string in C, you can use the strlen() function from the string.h library:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, World!";
int len = strlen(str1);
printf("The length of the string is: %d\n", len);
return 0;
}
Output:
The length of the string is: 13
String Concatenation
To concatenate two strings in C, you can use the strcat() function from the string.h library or manually allocate a larger array and copy the contents of both strings into it:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[10] = "World!";
// Concatenation using strcat()
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
// Manual concatenation by allocating a larger array and copying contents
char result[30];
strcpy(result, str1);
strcat(result, str2);
printf("Manually concatenated string: %s\n", result);
return 0;
}
Output:
Concatenated string: Hello, World!
Manually concatenated string: Hello, World!
Comparing Strings
To compare two strings in C, you can use the strcmp() function from the string.h library:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
int result = strcmp(str1, str2);
if (result < 0) {
printf("%s comes before %s.\n", str1, str2);
} else if (result > 0) {
printf("%s comes after %s.\n", str1, str2);
} else {
printf("%s is equal to %s.\n", str1, str2);
}
return 0;
}
Output:
Hello is equal to World.
Worked Example
Problem Statement
Write a C program that takes two strings as input and checks whether they are anagrams (strings formed by rearranging the letters of another string). If the strings are anagrams, print "Yes"; otherwise, print "No".
Solution
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int count_char(const char *str, char c) {
int count = 0;
for (int i = 0; str[i] != '\0'; ++i) {
if (tolower(str[i]) == tolower(c)) {
++count;
}
}
return count;
}
int main() {
char str1[50], str2[50];
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);
// Remove spaces and convert to lowercase
for (int i = 0; str1[i] != '\0'; ++i) {
if (!isspace(str1[i])) {
str1[i] = tolower(str1[i]);
}
}
for (int i = 0; str2[i] != '\0'; ++i) {
if (!isspace(str2[i])) {
str2[i] = tolower(str2[i]);
}
}
// Count characters in each string and compare
int counts[26] = {0};
for (int i = 0; str1[i] != '\0'; ++i) {
++counts[str1[i] - 'a'];
}
for (int i = 0; str2[i] != '\0'; ++i) {
++counts[str2[i] - 'a'];
}
int is_anagram = 1;
for (int i = 0; i < 26; ++i) {
if (counts[i] != counts[i + 26]) {
is_anagram = 0;
break;
}
}
printf(is_anagram ? "Yes\n" : "No\n");
return 0;
}
Common Mistakes
- Forgetting to include the necessary header files (string.h, stdio.h, ctype.h)
- Using the wrong function for a specific task (e.g., using strcat() instead of strcpy())
- Not handling input properly (e.g., forgetting to remove newline characters after fgets(), or not checking if the user entered the correct number of arguments)
- Not considering case sensitivity when comparing strings
- Not allocating enough memory for a string, leading to undefined behavior or segmentation faults
Practice Questions
- Write a C program that finds the longest common substring between two given strings.
- Write a C program that reverses a given string without using any built-in functions.
- Write a C program that checks if a given string is a palindrome (reads the same backward as forward).
- Write a C program that counts the number of occurrences of each character in a given string.
- Write a C program that replaces all occurrences of a specific substring within another string.
FAQ
- Why do we use null characters (\0) to mark the end of strings in C?
- Null characters help the program distinguish between individual strings and single characters, making it easier to manipulate strings using various functions from the
string.hlibrary.
- What is the difference between strcpy() and strcat() in C?
strcpy()copies the source string into the destination array, overwriting any existing contents.strcat()concatenates the source string to the end of the destination array without overwriting its original contents.
- How can I compare two strings case-insensitively in C?
- You can convert both strings to lowercase or uppercase before comparing them using the
tolower()andtoupper()functions from thectype.hlibrary.
- What is the maximum length of a string that can be declared as an array in C?
- The maximum length of a string that can be declared as an array in C depends on the system and compiler you are using, but it's usually limited to around 256 characters for practical purposes. For larger strings, consider using dynamic memory allocation with
malloc().
- What is the difference between strcmp() and strncmp() in C?
strcmp()compares two strings until it finds a null character or a difference in characters.strncmp()compares a maximum ofncharacters from both strings, wherenis specified as an argument, before checking for a null character or difference in characters. This can help prevent potential buffer overflows when comparing substrings.