C String Functions: Mastering String Manipulation
C programming offers a variety of string functions that facilitate performing different operations on strings. By including the <string.h>
header file in your program, you gain access to these essential functions, enabling you to manipulate and manage strings effectively in your applications.
C String Functions
String Functions
C provides several useful string functions that allow you to perform various operations on strings. To use these functions, you need to include the <string.h>
header file at the beginning of your program:
Syntax
#include <string.h>
String Length
To get the length of a string, you can use the strlen()
function. For example:
Example
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));
Output
26
Note that sizeof
and strlen
behave differently. While strlen
counts the number of characters in the string (excluding the null terminator \0
), sizeof
includes the null terminator in its count:
Example
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet)); // 26
printf("%d", sizeof(alphabet)); // 27
Output
26
27
Also, note that sizeof
always returns the memory size (in bytes) rather than the actual string length:
Example
char alphabet[50] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet)); // 26
printf("%d", sizeof(alphabet)); // 50
Output
26
50
Concatenate Strings
To concatenate (combine) two strings, you can use the strcat()
function:
Example
char str1[20] = "Hello ";
char str2[] = "World!";
// Concatenate str2 to str1 (result is stored in str1)
strcat(str1, str2);
// Print str1
printf("%s", str1);
Output
Hello World!
Make sure that the size of str1
is large enough to store the combined result of the two strings.
Copy Strings
To copy the value of one string to another, you can use the strcpy()
function:
Example
char str1[20] = "Hello World!";
char str2[20];
// Copy str1 to str2
strcpy(str2, str1);
// Print str2
printf("%s", str2);
Output
Hello World!
Ensure that the size of str2
is sufficient to hold the copied string.
Compare Strings
To compare two strings, you can use the strcmp()
function. It returns 0 if the strings are equal; otherwise, it returns a non-zero value:
Example
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";
// Compare str1 and str2, and print the result
printf("%d\n", strcmp(str1, str2)); // Returns 0 (the strings are equal)
// Compare str1 and str3, and print the result
printf("%d\n", strcmp(str1, str3)); // Returns a non-zero value (the strings are not equal)
Output
0
-1