C String Functions
The header file string.h has ready functions to work with strings. We must include it to use them.
Common string functions
| Function | Work |
|---|---|
strlen(s) | Returns the length of the string |
strcpy(dest, src) | Copies src to dest |
strncpy(dest, src, n) | Copies at most n characters |
strcat(dest, src) | Joins src at the end of dest |
strncat(dest, src, n) | Joins at most n characters |
strcmp(a, b) | Compares two strings |
strncmp(a, b, n) | Compares first n characters |
strchr(s, c) | Finds the first place of a character |
strstr(s, sub) | Finds a smaller string inside a string |
Example
#include <stdio.h>
#include <string.h>
int main(void) {
char a[30] = "Hello";
char b[] = " World";
strcat(a, b);
printf("%s\n", a);
printf("Length: %zu\n", strlen(a));
printf("Compare: %d\n", strcmp("apple", "apple"));
return 0;
}
Output:
Output of the above program is
Hello World
Length: 11
Compare: 0
Read each function in detail:
Note:
These functions do not check if the destination has enough space. You must make the array big enough, or use the n versions.
Next: C strlen() Function.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |