Introduction to C String Functions
In the C programming language, strings are a sequence of characters stored in an array. C provides a set of built-in functions specifically designed to manipulate and work with strings. These functions allow you to perform various operations on strings, such as copying, concatenating, comparing, and searching.
Commonly Used C String Functions
Here are some commonly used C string functions:
strlen()
The strlen()
function is used to determine the length of a string. It takes a string as input and returns the number of characters in the string, excluding the null character.
strcpy()
The strcpy()
function is used to copy a string from the source to the destination. It takes two arguments: the destination string and the source string. It copies the contents of the source string into the destination string, including the null character.
strcat()
The strcat()
function is used to concatenate or append one string to another. It takes two arguments: the destination string and the source string. It appends the contents of the source string to the end of the destination string, including the null character.
strcmp()
The strcmp()
function is used to compare two strings. It takes two strings as input and returns an integer value indicating the result of the comparison. 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.
strstr()
The strstr()
function is used to search for a substring within a string. It takes two strings as input and returns a pointer to the first occurrence of the substring in the main string. If the substring is not found, it returns a null pointer.
Example Usage
Let’s take a look at an example that demonstrates the usage of these string functions:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = "World";
printf("Length of str1: %dn", strlen(str1));
strcpy(str1, str2);
printf("After strcpy, str1: %sn", str1);
strcat(str1, " ");
strcat(str1, str2);
printf("After strcat, str1: %sn", str1);
int result = strcmp(str1, str2);
printf("Result of strcmp: %dn", result);
char* substring = strstr(str1, "lo");
printf("Substring found at: %sn", substring);
return 0;
}
Output:
Length of str1: 5
After strcpy, str1: World
After strcat, str1: World World
Result of strcmp: 0
Substring found at: lo World
C string functions are essential for manipulating and working with strings in the C programming language. They provide a convenient way to perform operations such as copying, concatenating, comparing, and searching strings. Understanding and using these functions effectively can greatly enhance your ability to work with strings in C.