strchr
函数原型:
#include <string.h>
char *strchr(const char *str, int c);功能:strchr 函数在给定的字符串 str 中查找指定字符 c 的首次出现位置,并返回该字符所在位置的指针。若找不到指定字符,则返回 NULL。
参数:
str:指向要搜索的字符串的指针。c:要查找的字符。
返回值:
如果在
str中找到字符c,返回指向该字符在str中位置的指针。如果在
str中未找到字符c,返回NULL。
示例:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strchr(str, ',');
if (ptr != NULL) {
printf("Found character ',' at position %td\n", ptr - str + 1);
} else {
printf("Character not found in the string.\n");
}
return 0;
}strrchr
函数原型:
#include <string.h>
char *strrchr(const char *str, int c);功能:strrchr 函数与 strchr 类似,但它是从字符串末尾向前搜索,返回指定字符 c 在字符串 str 中最后一次出现的位置的指针。
参数:
str:指向要搜索的字符串的指针。c:要查找的字符。
返回值:
如果在
str中找到字符c,返回指向该字符在str中位置的指针。如果在
str中未找到字符c,返回NULL。
示例:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!, Hello again!";
char *ptr = strrchr(str, ',');
if (ptr != NULL) {
printf("Found character ',' at position %td\n", ptr - str + 1);
} else {
printf("Character not found in the string.\n");
}
return 0;
}在这段示例中,strrchr 函数会找到字符串中最后一个逗号 , 的位置。如果字符串中有多个相同的字符,strchr 返回的是第一个匹配项,而 strrchr 返回的是最后一个匹配项。
评论区