主页 > 其他  > 

每日学习总结20240301


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。

标签:

每日学习总结20240301由讯客互联其他栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“每日学习总结20240301