首页 > 其他 > 详细

[C]如何用strchr来找字符串中所有的char

时间:2020-06-18 20:52:10      阅读:53      评论:0      收藏:0      [点我收藏+]

找出字符串Bienvenidos a todos中所有的字符e

#include <stdio.h>
#include <string.h>
int main() {
    char s[] = "Bienvenidos a todos";
    char * p = strchr(s, e); //通过这个方法找到了第一个e的地址,如何找下一个e呢?
    printf("%s\n", p); //输出结果
    p = strchr(p+1, e); //把地址移到一个,然后再开始找
    printf("%s\n", p);
    p = strchr(p+1, e); //我们可以用同样的方法,一直找下去,只要指针不返回nil,所以我们可以通过while循环来找遍所有的e
    printf("%p\n", p); //这时指针返回nil了
    printf("%s\n", p); //程序会在这里collapse
    return 0;
}

 

用while来找遍所有的e

int main() {
// while循环来找遍所有的e
    char s[] = "Bienvenidos a todos";
    char * p = strchr(s, e);
    while (p) { //只要p不是0,一直找下去,这里因为不知道循环的次数,所以用while循环,不建议用for循环
        printf("%s\n", p);
        p = strchr(p+1, e);
    }
}

 

[C]如何用strchr来找字符串中所有的char

原文:https://www.cnblogs.com/profesor/p/13159386.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!