The functions in the C string handling library can be used to manage strings. String operations are carried out using the string.h library. It offers a number of functions for working with strings.
Several frequently used string handling functions are listed below:
- Strcat() is a function that joins the end of the source and destination strings together. The base addresses of the source string and the target string are the first two parameters this method expects. For instance, the string “HelloWorld” would be produced by concatenating the words “Hello” and “World.”
The strcat() function can be used as shown below:
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "Hello";
char t[] = "World";
strcat(s, t);
printf("String = %s", s);
}
Output
String = HelloWorld
- The strlen() method counts the amount of characters in a string.
The strlen() method can be used as shown below:
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "Hello";
int len = strlen(s);
printf("Length = %d", len);
}
Output:
Length = 5
- The strcpy() method copies the data from one string into another. The base addresses of the source string and the target string are the first two parameters this method expects.
The strcpy() method can be used in the following ways:
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "studentproject";
char t[50];
strcpy(t, s);
printf("Source string = %s\n", s);
printf("Target string = %s", t);
}
Output:
Source string = studentproject
Target string = studentproject
- strcmp() This function compares two strings to determine whether they are identical or dissimilar. It accepts two strings as parameters. Character by character, it will compare two strings until it finds a discrepancy or reaches the end of one of the strings.A value of zero is returned by strcmp() if the strings are identical. If the two strings are not identical, it will return a number that is less than zero because the mismatched character in the first string has a lower ASCII value than the mismatched character in the second. Otherwise, a value other than 0 will be returned.
The strcmp() function can be utilised as shown below:
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "Hello";
char t[] = "World";
int cmp = strcmp(s, t);
printf("Comparison result = %d", cmp);
}
Output:
Comparison result = -1
- strrev() This function is used to return the reverse of the string. Here is how we can use the strrev( ) function:
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "project";
printf("Reversed string = %s", strrev(s));
}
Output:
Reversed string = tcejorp