找出字符串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 ", p); //输出结果 p = strchr(p+1, 'e'); //把地址移到一个,然后再开始找 printf("%s ", p); p = strchr(p+1, 'e'); //我们可以用同样的方法,一直找下去,只要指针不返回nil,所以我们可以通过while循环来找遍所有的e printf("%p ", p); //这时指针返回nil了 printf("%s ", 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 ", p); p = strchr(p+1, 'e'); } }