1. strstr()函数
strstr()
函数用于在一个字符串中查找指定子字符串的首次出现位置。它的函数原型如下:
char *strstr(const char *str1, const char *str2);
str1
:要在其中查找的字符串。str2
:要查找的子字符串。
strstr()
函数返回一个指向子字符串在源字符串中首次出现位置的指针,如果没有找到,则返回NULL
。
下面是一个示例代码,演示了strstr()
函数的用法:
#include <stdio.h>
#include <string.h>
int main() {
const char *str1 = "This is a sample string";
const char *str2 = "sample";
char *position = strstr(str1, str2);
if (position != NULL) {
printf("'%s' was found at position: %ld\n", str2, position - str1);
} else {
printf("'%s' was not found\n", str2);
}
return 0;
}
输出结果为:
'sample' was found at position: 10
2. strtok()函数
strtok()
函数用于将字符串分割成一系列子字符串,它的函数原型如下:
char *strtok(char *str, const char *delimiters);
str
:要分割的字符串。delimiters
:分割符号串,用于指定分割的位置。
strtok()
函数返回一个指向分割后的子字符串的指针,如果没有可分割的子字符串,则返回NULL
。
下面是一个示例代码,演示了strtok()
函数的用法:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "apple,banana,cherry";
const char delimiters[] = ",";
char *token = strtok(str, delimiters);
while (token != NULL) {
printf("Token: %s\n", token);
token = strtok(NULL, delimiters);
}
return 0;
}
输出结果为:
Token: apple
Token: banana
Token: cherry
3. strerror()函数
strerror()
函数用于获取与 errno 相对应的错误消息字符串。它的函数原型如下:
char *strerror(int errnum);
errnum
:错误码,通常是errno
的值。
strerror()
函数返回一个指向错误消息字符串的指针。
下面是一个示例代码,演示了strerror()
函数的用法:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
FILE *file = fopen("nonexistentfile.txt", "r");
if (file == NULL) {
printf("Failed to open file: %s\n", strerror(errno));
}
return 0;
}
输出结果为:
Failed to open file: No such file or directory