C语言strrchr函数详解:查找字符串中最后一个字符
strrchr函数是C语言中的一个字符串处理函数,用于查找字符串中最后一个出现的指定字符的位置,并返回指向该位置的指针。
函数原型为:
char *strrchr(const char *str, int c);
其中,'str'为要查找的字符串,'c'为要查找的字符。函数返回一个指向最后一个出现该字符的位置的指针,如果未找到该字符,则返回NULL。
例如,以下代码将查找字符串'str'中最后一个出现字符'.'的位置:
char str[] = 'www.example.com';
char *ptr = strrchr(str, '.');
if (ptr != NULL) {
printf('Last occurrence of '.' found at position %ld\n', ptr - str);
} else {
printf('Character '.' not found in string\n');
}
输出结果为:
Last occurrence of '.' found at position 11
注意,strrchr函数返回的指针指向的是字符串中的位置,而不是字符串中的字符。因此,如果需要获取该字符的位置,需使用指针减去字符串的起始地址。
原文地址: https://www.cveoy.top/t/topic/m36L 著作权归作者所有。请勿转载和采集!