1. strcat()
将源字符串(src
)追加到目标字符串(dest
)的末尾
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello";
char src[] = " World!";
strcat(dest, src); // 将 src 追加到 dest
printf("Result: %s\n", dest); // 输出: Hello World!
return 0;
}
2. strncat()
将源字符串(src
)的前 n
个字符追加到目标字符串(dest
)的末尾
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello";
char src[] = " World!";
strncat(dest, src, 3); // 将 src 的前 3 个字符追加到 dest
printf("Result: %s\n", dest); // 输出: Hello Wo
return 0;
}
3. strstr()
在字符串 haystack
中查找子字符串 needle
的第一次出现位置
#include <stdio.h>
#include <string.h>
int main() {
const char *haystack = "Hello World!";
const char *needle = "World";
char *result = strstr(haystack, needle);
if (result) {
printf("Found: %s\n", result); // 输出: Found: World!
} else {
printf("Not found!\n");
}
return 0;
}
4. strtok()
将字符串 str
按照指定的分隔符(delim
)分割成多个子字符串(标记)
- 第一次调用时,
str
是要分割的字符串;后续调用时,str
应为NULL
。 - strtok 会修改原始字符串,将分隔符替换为 \0
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello,World,How,Are,You";
const char *delim = ",";
char *token = strtok(str, delim);
while (token) {
printf("Token: %s\n", token);
token = strtok(NULL, delim);
}
return 0;
}
5. strerror()
返回错误码对应的错误信息字符串
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (!file) {
printf("Error: %s\n", strerror(errno)); // 输出错误信息
}
return 0;
}
6. perror()
打印自定义信息以及会将错误码转化为错误信息输出
int main()
{
FILE* pf = fopen("test.txt", "r");
if(pf == NULL)
{
perror("fopen");
}
}
🦀🦀观看~