20240301
1. strchr VS strrchr
strchr和strrchr是C语言标准库中的字符串处理函数,用于在字符串中查找特定字符的位置。
1.1 strchr函数
strchr函数用于在字符串中查找第一次出现指定字符的位置,并返回该位置的指针。函数原型如下:
char *strchr(const char *str, int c);
str:要在其中搜索的字符串。c:要查找的字符的ASCII值。
strchr函数会返回一个指向第一次出现指定字符的指针。如果未找到指定字符,则返回NULL。
示例用法:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strchr(str, 'W');
if (ptr != NULL) {
printf("Found 'W' at position: %ld\n", ptr - str);
} else {
printf("Character not found.\n");
}
return 0;
}
输出将是:
Found 'W' at position: 7
1.2 strrchr函数
strrchr函数与strchr函数类似,但是它在字符串中从右向左查找指定字符,并返回最后一次出现的位置的指针。函数原型如下:
char *strrchr(const char *str, int c);
参数与strchr函数相同。
strrchr函数会返回一个指向最后一次出现指定字符的指针。如果未找到指定字符,则返回NULL。
示例用法:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strrchr(str, 'o');
if (ptr != NULL) {
printf("Found 'o' at position: %ld\n", ptr - str);
} else {
printf("Character not found.\n");
}
return 0;
}
输出将是:
Found 'o' at position: 8
总结:
strchr函数在字符串中查找第一次出现指定字符的位置。strrchr函数在字符串中查找最后一次出现指定字符的位置。- 如果指定字符未找到,两个函数都会返回
NULL。



















