C语言中的strchr和strrchr函数
在C语言中,strchr
和strrchr
函数是用于在字符串中查找指定字符的标准库函数。它们可以用来查找一个字符串中是否包含指定字符,并返回该字符在字符串中的位置。
函数原型
strchr
函数的原型如下:
char *strchr(const char *str, int c);
strrchr
函数的原型如下:
char *strrchr(const char *str, int c);
这两个函数的参数都包括:
str
:指向要搜索的字符串的指针。c
:要查找的字符。
函数返回值为指向第一次出现或最后一次出现指定字符的位置的指针,如果没有找到,则返回NULL
。
函数功能
strchr
函数的功能是在一个字符串中查找指定字符,并返回该字符在字符串中的位置。
strrchr
函数的功能是在一个字符串中查找指定字符的最后一个出现位置,并返回该位置的指针。
函数实现
下面是strchr
函数的一个简单实现:
char *strchr(const char *str, int c) {
while (*str != '\0') {
if (*str == c) {
return (char *)str;
}
str++;
}
if (*str == c) {
return (char *)str;
}
return NULL;
}
该实现的思路是,使用while
循环将字符串中的每个字符逐个与指定字符进行比较,如果出现相等的字符,则返回该字符在字符串中的位置。
下面是strrchr
函数的一个简单实现:
char *strrchr(const char *str, int c) {
const char *last = NULL;
while (*str != '\0') {
if (*str == c) {
last = str;
}
str++;
}
if (*str == c) {
return (char *)str;
}
return (char *)last;
}
该实现的思路是,使用while
循环将字符串中的每个字符逐个与指定字符进行比较,如果出现相等的字符,则记录该字符在字符串中的位置;最后返回最后一个出现该字符的位置。
使用示例
下面是一个使用strchr
函数的示例:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
char ch = 'o';
char *result = strchr(str, ch);
if (result == NULL) {
printf("The character is not found.\n");
} else {
printf("The character is found at position %ld.\n", result - str);
}
return 0;
}
该示例在字符串"Hello, world!"
中查找字符'o'
,输出结果为:
The character is found at position 4.
下面是一个使用strrchr
函数的示例:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
char ch = 'o';
char *result = strrchr(str, ch);
if (result == NULL) {
printf("The character is not found.\n");
} else {
printf("The character is found at position %ld.\n", result - str);
}
return 0;
}
该示例在字符串"Hello, world!"
中查找字符'o'
的最后一个出现位置,输出结果为:
The character is found at position 8.
总结
strchr
和strrchr
函数是用于在字符串中查找指定字符的标准库函数,可以用来查找一个字符串中是否包含指定字符,并返回该字符在字符串中的位置。它们的使用方法比较简单,只需要指定要查找的字符即可。需要注意的是,如果没有找到指定字符,则返回NULL
。