How to use the functions in the string.h of the C language?
In the C language, functions in the string.h header file can be used to manipulate strings. Here are some commonly used functions and their usage methods:
- Copy the string src to the string dest.
#include <string.h>
int main() {
char str1[10];
char str2[10] = "Hello";
strcpy(str1, str2);
printf("%s\n", str1); // 输出: Hello
return 0;
}
- append the string src to the end of the string dest.
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[10] = " World";
strcat(str1, str2);
printf("%s\n", str1); // 输出: Hello World
return 0;
}
- Get the length of the string.
#include <string.h>
int main() {
char str[10] = "Hello";
int len = strlen(str);
printf("%d\n", len); // 输出: 5
return 0;
}
- The function strcmp() compares two strings. It returns 0 if the strings are equal, a value greater than 0 if str1 is greater than str2, and a value less than 0 if str1 is less than str2.
#include <string.h>
int main() {
char str1[10] = "Hello";
char str2[10] = "Hello";
int result = strcmp(str1, str2);
printf("%d\n", result); // 输出: 0
return 0;
}
These functions are just a part of string.h; there are many other functions available for string operations. Depending on your specific needs, you can refer to the relevant documentation to learn about more functions that can be used.