String Manipulation in C
Introduction
Strings in C are arrays of characters terminated by a null character ('\0'
). This null character is used to indicate the end of the string. String manipulation involves various operations that can be performed on strings, such as copying, concatenation, comparison, and searching.
Declaring and Initializing Strings
Strings can be declared and initialized in several ways in C:
char str1[20]; // Declares a string of size 20 char str2[] = "Hello, World!"; // Initializes with a string literal char str3[20] = "Hello"; // Declares with specific size and initializes
String Input and Output
To read and write strings, we typically use the scanf
and printf
functions:
#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); scanf("%s", name); printf("Hello, %s!\n", name); return 0; }
Note: scanf
stops reading input at the first whitespace character. To read a line of text, consider using fgets
instead:
#include <stdio.h> int main() { char name[50]; printf("Enter your full name: "); fgets(name, sizeof(name), stdin); printf("Hello, %s", name); return 0; }
String Length
The strlen
function from the string.h
library is used to get the length of a string:
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello, World!"; int length = strlen(str); printf("Length of the string: %d\n", length); return 0; }
String Copy
The strcpy
function is used to copy the content of one string to another:
#include <stdio.h> #include <string.h> int main() { char src[] = "Hello, World!"; char dest[20]; strcpy(dest, src); printf("Copied string: %s\n", dest); return 0; }
String Concatenation
The strcat
function is used to concatenate two strings:
#include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello"; char str2[] = ", World!"; strcat(str1, str2); printf("Concatenated string: %s\n", str1); return 0; }
String Comparison
The strcmp
function is used to compare two strings. It returns 0 if the strings are equal, a positive value if the first string is greater, and a negative value if the second string is greater:
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello"; char str2[] = "World"; int result = strcmp(str1, str2); if (result == 0) { printf("Strings are equal\n"); } else if (result > 0) { printf("str1 is greater than str2\n"); } else { printf("str1 is less than str2\n"); } return 0; }
String Searching
The strstr
function is used to find the first occurrence of a substring in a string. It returns a pointer to the first occurrence of the substring, or NULL
if the substring is not found:
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello, World!"; char *substr = strstr(str, "World"); if (substr != NULL) { printf("Substring found: %s\n", substr); } else { printf("Substring not found\n"); } return 0; }