In this article, we explain how the various built-in C string functions can be used to perform various operations, including string manipulation, comparison, concatenation, etc.
A string is an array of characters that ends with a null termination. When working with strings, there are situations where we may need to transform the information. In such a scenario, instead of writing the logic, we can use the built-in string functions in C language.
The <string.h> header file holds the C string functions, and these built-in library methods are meant to operate only on strings. To utilize these methods, we must include <string.h> header file inside a program.
TIP: Please refer to the String article to understand everything about strings.
List of C String Functions
The <string.h> header file has many built-in string functions that allow you to perform a wide variety of tasks on strings.
The following table is a list of available string functions in the C Programming language for performing string operations. Within the list below, some non-standard ones may not work on Linux.
| C String Functions | Description |
|---|---|
| strcat | To concat or combine two strings. It appends a user-specified string to the end of another string. |
| strncat | This is the same as above. However, you can restrict the total number of characters to append. |
| strcmp | It is used to lexicographically compare two strings and check whether they are equal or not. |
| strncmp | This function is similar to strcmp(). However, you can restrict the total number of characters to compare. |
| strcpy | Used to shallow copy a given string into the destination. |
| strncpy | This is the same as strcpy. However, you can restrict the number of characters to copy. |
| strcoll | Using LC_COLLATE settings (locale settings), it will compare the two strings. |
| strcspn() | It returns the length of a given string until it finds any of the characters in the second set. |
| strspn() | Returns the length of the initial segment of a text that only contains the characters from the second string. |
| strlen | It finds the total number of characters or the length of a string, excluding the null terminator. |
| strlwr | Converts a given string to lowercase. |
| strpbrk | It finds the first character in the first one that matches any character in the second one. |
| strrev | Use this to reverse. |
| strupr | Converts the given string of characters to uppercase. |
| strtok | It helps to tokenize the string using the given delimiter. |
| strrchr | This function finds the last occurrence of a given character in a string. |
| strchr | It finds the first occurrence of a given character in a string. |
| strstr | It finds the first occurrence of a substring (group of characters) in a string. |
| strset() | It replaces all characters in a string with a specific character. |
| strnset() | It sets a limited number of characters in a given string to a specified character. |
| strxfrm() | This function first transforms the given string and performs locale-based string comparison. |
| strcasecmp() | It performs a case-sensitive comparison between the two given strings. |
| strncasecmp() | It performs a case-sensitive comparison on a limited number of characters from the two strings. |
| strpbrk() | It searches for the first occurrence of any of the given set of characters within a string. |
| strerror() | It returns the meaning of an error code. |
| sprintf() | Using the format specifier, it formats the given text and stores it in a string buffer. |
| strdup() | It returns a duplicate of a given string. |
| memchr | It finds the first occurrence of a character and returns a pointer to it. |
| memcmp() | Compares N bytes from two blocks of memory. |
| memcpy() | It copies string data from one block of memory to another. |
| memmove() | Another function for copying N bytes from one block of memory to another. |
| memset() | Setting all bytes pointing to this memory to the same value. |
C string functions to find the length
The following list of functions finds the length or total number of characters in a string.
strlen()
The strlen() function finds the length of a string. In other words, the strlen() function returns the total number of characters in a given string, excluding ‘\0’ (Null terminator).
#include <stdio.h>
#include<string.h>
int main()
{
char name[] = "United States";
int len = strlen(name);
printf("%d", len);
return 0;
}
13
C string functions – strnlen()
The strnlen() function accepts two arguments, where the second argument is the maximum length value. Unlike strlen(), the strnlen() function returns the length of a given string if it is less than the specified max value (Second argument).
In the following example, the first printf() statement returns the original string length. However, the second statement returns 10 because we set the maximum length value to 10. So, instead of 13, the strnlen() function returns 10.
#include <stdio.h>
#include<string.h>
int main()
{
char name[] = "United States";
printf("%d", strnlen(name, 20));
printf("\n%d", strnlen(name, 10));
return 0;
}
Result
13
10
strcspn()
The strcspn() function accepts two arguments, where the second argument is the set of characters it has to reject. Unlike strlen(), the strcspn() string functions in C returns the length of a given string until it finds any of the characters in the second set (Second argument).
In the following example, the strcspn() function returns 3 as the output. Here, “s1” is a group of three words separated by a space. The second string has a blank space and a full stop. It means the strcspn() function finds the length of s1 until it finds either a blank space or a full stop.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "The United States.";
char s2[] = " .";
printf("%d", strcspn(s1, s2));
return 0;
}
3
C string functions – strspn()
Unlike strcspn(), the strspn() function finds the length of the initial segment of a given string that only contains the characters from the second argument.
In the following example, the strspn() function returns 6 as the output. Here, the first six characters in “s1” are present in the second argument (“s2” ).
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "United123";
char s2[] = "United";
printf("%d", strspn(s1, s2));
return 0;
}
6
C string functions to copy a string
Both the strcpy() and strncpy() functions copies string from source to destination.
strcpy()
The strcpy() function accepts two arguments and copies an entire string from the given source to the destination. If there is any existing text in the destination, it will be replaced by the source data.
TIP: The strcpy() copies the entire string, including the null terminator at the end. So, the destination must have enough space to store the incoming text.
The following C string functions example uses strcpy() and copies the entire string in s1 into s2. As there is existing content in “s2”, it will be replaced by the “s1” text.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "United Kingdom";
char s2[] = "European Union";
strcpy(s2, s1);
printf("%s", s2);
return 0;
}
United Kingdom
strncpy()
The strncpy() function accepts three arguments and copies a given number of bytes (characters) from the source to the destination. Unlike strcpy(), the strncpy() function copies only a limited number of bytes, and they are decided by the third argument.
We can use the strncpy() function to copy a limited number of characters. If you observe the C string functions program below, the strncpy() copies only 6 bytes (United) from the source to the destination.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "United Kingdom";
char s2[10];
strncpy(s2, s1, 6);
printf("%s", s2);
return 0;
}
United
C string functions to perform concatenation
The strcat() and strncat() functions are helpful in performing string concatenation or joining.
strcat()
The strcat() function is used to perform string concatenation or combine two strings to form along text. It accepts two arguments and appends the text from the second argument to the end of the first argument.
TIP: Use the strcat() function to join strings. Always check the space in the first string to store the text from the second.
The following C string functions example uses strcat() and joins the s2 string at the end of the s1 string. Notice the small space after United in the first string.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "United ";
char s2[] = "States";
printf("%s", strcat(s1, s2));
return 0;
}
United States
strncat()
Unlike the strcat(), the strncat() string functions in C accept three arguments to perform string concatenation. Instead of concatenating the whole string, the strncat() joins only a limited number of characters at the end of the source string. The third argument determines how many characters the strncat() function concatenates.
The following example joins only six characters from the s2 string at the end of the s1 string. Although the s2 string has “States of America” text, the strncat() function joins only the “States” text because the third argument is restricted to 6.
TIP: Use the strcat() function to unconditionally join the strings. On the other hand, use the strncat() function to append a limited number of characters.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[50] = "The United ";
char s2[20] = "States of America";
strncat(s1, s2, 6);
printf("%s", s1);
return 0;
}
The United States
C string functions to perform comparison
When working with text information, string comparison is a key aspect to perform. The following strcmp(), strncmp(), strcasecmp(), strncasecmp(), strcoll(), and strxfrm() functions are the built-inC sting functions to perform.
strcmp()
The strcmp() function accepts two string arguments, compares those two strings lexicographically, and returns an integer value. For example, consider s1 and s2.
- 0 – If both are equal.
- If s1 is less than s2, it returns a value less than 0 (Negative).
- If s1 is greater than s2, it returns a value greater than 0 (Positive).
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "India";
char s2[] = "Indi";
int result = strcmp(s1, s2);
if(result == 0)
{
printf("Both are Equal");
}
else if(result > 0)
{
printf("s1 is Greater than s2");
}
else {
printf("s1 is Less than s2");
}
return 0;
}
s1 is Greater than s2
NOTE: Please change the ‘s2’ word from ‘Indi’ to ‘India’ and ‘Indian’ to see the positive and 0 result.
strncmp()
Unlike strcmp(), the strncmp() string functions in C language accepts three arguments to perform string comparison. The strncmp() function compares the first N characters of the two given strings lexicographically. The return value is the same as that of strcmp.
Instead of comparing the whole string, the strncmp() compares only a limited number of characters. The third argument determines the characters that the strncmp() compares.
As we have already explained, in the above example, the else if statement, this time we won’t display a message. The following example will return the positive, negative, or zero result.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "Indian";
char s2[] = "Indi";
printf("%d", strncmp(s1, s2, 4));
printf("\n%d", strncmp(s1, s2, 5));
printf("\n%d", strncmp(s2, s1, 6));
return 0;
}
Result
0
1
-1
C string functions – strcasecmp()
The strcmp() function performs case-sensitive comparison of the two strings. So, we can use the strcasecmp() function to perform case-sensitive comparison. Similar to the strcmp(), the strcasecmp() function accepts two arguments and performs string comparison without checking the character case.
NOTE: For the strcmp() function, lowercase and uppercase characters are different. On the other hand, the strcasecmp() function treats lower and upper case characters as the same.
The following example compares the uppercase “INDIA” against the lowercase “indi”. As the strcasecmp() function does not treat them differently, it only looks for the characters and displays a positive number, a negative value, or a zero result.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "INDIA";
char s2[] = "indi";
printf("%d", strcasecmp(s1, s2));
printf("\n%d", strcasecmp(s2, s1));
printf("\n%d", strcasecmp("INDIA", "india"));
return 0;
}
Result
97
-97
0
C string functions – strncasecmp()
Unlike the strcasecmp() function, the strncasecmp() function performs case-sensitive comparison on a limited number of characters from the two strings.
Instead of comparing the complete string, the strncasecmp() compares only a limited number of characters. The third argument determines the characters that the strncasecmp() compares.
The following example compares the uppercase “INDIA” against the lowercase “indi” with characters limited to 4, 5, and 6. So, instead of checking the whole string, the strncasecmp() function compares the first four, five, and six characters of s1 and s2.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "INDIAN";
char s2[] = "Indi";
printf("%d", strncasecmp(s1, s2, 4));
printf("\n%d", strncasecmp(s1, s2, 5));
printf("\n%d", strncasecmp(s2, s1, 6));
return 0;
}
Result
0
97
-97
strcoll()
The strcoll() function is helpful while working with different languages. The strcoll() function performs the string comparison based on the current locale settings.
In general, “ä” comes after “z”, whereas in the German language, it is considered as ae. If you remove the “setlocale(LC_COLLATE, “”);” statement, as per my locale system settings, the result becomes äpple comes after apple.
#include <stdio.h>
#include <string.h>
#include <locale.h>
int main() {
char s1[] = "äpple";
char s2[] = "apple";
setlocale(LC_COLLATE, "");
int result = strcoll(s1, s2);
if (result < 0) {
printf("%s comes before %s", s1, s2);
} else if (result > 0) {
printf("%s comes after %s", s1, s2);
} else {
printf("%s is equal to %s", s1, s2);
}
return 0;
}
äpple comes before apple
C string functions – strxfrm()
Similar to the strcoll() function, the strxfrm() function performs locale-based string comparison. However, the strfrm() function first transforms the given string and then compares both strings.
NOTE: The transformed text returned by the strxfrm() function might look different. So, don’t get confused by seeing the output.
#include <stdio.h>
#include <string.h>
#include <locale.h>
int main() {
char s1[] = "apple";
char s2[] = "apple";
char t1[20], t2[20];
setlocale(LC_COLLATE, "");
strxfrm(t1, s1, sizeof(t1));
strxfrm(t2, s2, sizeof(t2));
printf("Transformed s1: %s\n", t1);
printf("Transformed s2: %s\n", t2);
int result = strcmp(t1, t2);
printf("Comparison result: %d\n", result);
return 0;
}
Result
Transformed s1: ~~H!
Transformed s2: ~~H!
Comparison result: 0
C string functions to perform search operations
The strchr(), strnchr(), strstr(), and strpbrk() functions help perform search operations on existing strings. It can be a character or a substring; these built-in C string functions are the ones to look for.
strchr()
The strchr() function finds and returns the first occurrence of a given character within a string. If the given character is found, it returns a pointer (address) to the first occurrence position. Otherwise, it returns the NULL value.
We can use the strchr() function in two ways: to print the substring starting from the given character or to find the index position.
In the following C string functions example, we declared a string to utilize two possibilities of strchr(). As the strchr() returns a pointer, loc stores the address of the first occurrence of ‘e’. Next, we print the index position of the character. The last printf() statement prints the substring starting from the first occurrence of ‘s’ to the end of the string.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "united states";
char *loc = strchr(s1, 'e');
printf("%ld", loc - s1);
printf("\n%s", strchr(s1, 's'));
return 0;
}
4
states
strrchr()
Similar to the strchr(), the strrchr() function finds the last occurrence of a character in a string. The strrchr() function finds and returns the last occurrence of a character within a given string. If the character is found, it returns a pointer to the last occurrence position. Otherwise, it returns the NULL value.
In the following example, we use the strrchr() function to find the last occurrence of the ‘t’ character in a string. The first printf() statement returns the index position, and the second one returns the substring starting from ‘t’.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "united states";
char *loc = strrchr(s1, 't');
printf("%ld", loc - s1);
printf("\n%s", strrchr(s1, 't'));
return 0;
}
10
tes
strstr()
The strstr() function is used to search for the first occurrence of a given substring within a string. If the substring is found, it returns a pointer (address) to the index position of the first occurrence. Otherwise, it returns the NULL value.
In the following C string functions strstr() example, the first printf statement returns the index position of the first occurrence of “states”. The last printf() statement prints the substring starting from the first occurrence of ‘states’ to the end of the string.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "United states and Arab states";
char *loc = strstr(s1, "states");
printf("%ld", loc - s1);
printf("\n%s", strstr(s1, "states"));
return 0;
}
Result
7
states and Arab states
TIP: Use the strchr() function to find a character and the strstr() function to find a substring within a string.
strpbrk()
The strpbrk() function allows a set of characters and search the first occurrence of any of those characters within a string. If the given character is found, it returns a pointer to the first occurrence position. Otherwise, it returns the NULL value.
Unlike the strchr() function, the strpbrk() function allows searching multiple characters at a time. For example, in the C string functions program below, the strpbrk() function searches for the first occurrence of “t” or “s”. As “t” comes first, it returns the index position and the substring starting with “t”.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "united states";
char *loc = strpbrk(s1, "ts");
printf("%ld", loc - s1);
printf("\n%s", strpbrk(s1, "ts"));
return 0;
}
Result
3
ted states
C string functions for upper and lower case
The strlwr() and strupr() functions convert the existing string to either lowercase or uppercase.
strlwr()
The strlwr() function converts all characters in the user-given string to lowercase.
#include <stdio.h>
#include<string.h>
int main()
{
char name[] = "United NATIONS";
printf(strlwr(name));
return 0;
}
united nations
strupr()
The strupr() function converts the user-given string to uppercase.
#include <stdio.h>
#include<string.h>
int main()
{
char name[] = "United Nations";
printf(strupr(name));
return 0;
}
UNITED NATIONS
Other string functions in C language
strrev()
The strrev() function is useful for reversing a given string. It takes the whole string and reverses the complete text. The following example uses the strrev() function to reverse the “United States” word.
#include <stdio.h>
#include<string.h>
int main()
{
char name[] = "United States";
printf("%s", strrev(name));
return 0;
}
setatS detinU
C string functions – strerror()
The strerror() function converts the error codes or errono generated in run-time into a simple string message, so that the user can read them. Instead of seeing the error number, this message easily helps with debugging code.
#include <stdio.h>
#include <string.h>
int main()
{
printf("%s\n", strerror(2));
return 0;
}
No such file or directory
sprintf()
Unlike the regular printf() statement, the sprintf() function uses a format specifier to format a given string and stores it in a string buffer. Instead of displaying the result or message as the output, it stores it in the buffer.
In the following C string functions sprintf() example, the string “The Sum of 5 and 45 is 50” is stored inside the “s” variable.
#include <stdio.h>
int main() {
char s[100];
int a = 5, b = 45;
sprintf(s, "The Sum of %d and %d is %d", a, b, a + b);
printf("%s", s);
return 0;
}
The Sum of 5 and 45 is 50
strtok()
The strtok() function splits the given string into tokens based on the specified delimiter. Here, the second argument determines the splitting delimiter.
In the following C string functions example, we use the strtok() function to split the string message using a comma delimiter.
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "Hi,hello,welcome,you,all";
char *words = strtok(s, ",");
while (words != NULL)
{
printf("%s\n", words);
words = strtok(NULL, ",");
}
return 0;
}
Result
Hi
hello
welcome
you
all
strset()
The strset() function is a non-standard C programming function that sets all characters in a given string to a specified character. We can use the strset() function to replace the total string with a single repeated character (like a mask).
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Kingdom";
strset(s, 'H');
printf("%s\n", s);
return 0;
}
HHHHHHH
C string functions – strnset()
Similar to the strset(), strnset() is a non-standard C programming function that sets a limited number of characters in a given string to a specified character.
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Kingdom";
strnset(s, 'M', 4);
printf("%s\n", s);
return 0;
}
MMMMdom
strdup()
The strdup() function is not a standard function, but it is helpful to duplicate a given string. Unlike strcpy(), it allocates memory, copies the complete string, and manages it. We can use the free() function to avoid memory leaks.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
const char *s1 = "Hello world!";
char *s2 = strdup(s1);
printf("Original = %s\n", s1);
printf("Copy = %s", s2);
free(s2);
return 0;
}
Result
Original = Hello world!
Copy = Hello world!
C string functions for memory manipulation
Memory management is a crucial thing while coding in the C language. There are a few memory manipulation functions that allow you to manipulate the data directly inside a memory block. Although they are string-specific, we can use them to perform string operations.
Before diving deeper into the memory manipulation string functions in C language, let me give a quick summary to understand these methods.
- memcpy(): Copy without checking overlaps.
- memmove(): Safe copying of string data.
- memcmp(): memory level string comparison.
- memchr(): finding bytes.
- memset(): Fill memory with a single character.
memcpy()
The memcpy() function copies the total number of bytes in one block of memory to another block. Since it is memory-level operations, it is faster than the traditional approach.
NOTE: It does not check for memory overlaps.
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "States";
char d[10];
memcpy(d, s, sizeof(s));
printf("%s\n", d);
return 0;
}
States
If you set the third argument value less than the actual string, it copies only a few characters. For instance, sizeof(s) – 3 returns “hel”.
memmove()
Similar to the memcpy(), the memmove() function moves bytes in one block of memory to another. However, the memmove() function handles the memory overlaps and ensures safer data transit.
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "India";
memmove(s + 2, s, 3);
printf("%s\n", s);
return 0;
}
InInd
C string functions – memcmp()
The memcmp() function compares the content in two blocks of memory byte by byte and returns a positive, negative integer, or zero. The result set is the same as the strcmp() function.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "Indian";
char s2[] = "Indi";
printf("%d", memcmp(s1, s2, 4));
printf("\n%d", memcmp(s1, s2, 5));
printf("\n%d", memcmp(s2, s1, 5));
return 0;
}
Result
0
1
-1
memchr()
The memchr() function searches for a given character within a block of memory. If it finds, it returns the pointer to the address; otherwise, it returns a NULL value. Here, the third argument is the length; the search operation happens up to that point. In the second printf statement, we used 6, and within the first six characters, there is no ‘s’, so it returns NULL.
#include <stdio.h>
#include<string.h>
int main()
{
char s1[] = "united states";
char *loc = memchr(s1, 'e', 5);
printf("%ld", loc - s1);
printf("\n%s", memchr(s1, 's', 6));
return 0;
}
Result
4
(null)
C string functions -memset()
The memset() function resets the block of memory to a user-specified character. It simply replaces all bytes in that memory block with a single character. The following example sets the memory block with the ‘G’ value.
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "SHELTER";
memset(s, 'G', strlen(s));
printf("%s\n", s);
return 0;
}
GGGGGGG