c语言学习——在一个字符串中查找另个字符串字符

c语言学习——在一个字符串中查找另个字符串字符c 和指针的一个 6 1 习题 在字符串 str 中字符 查找在字符串 source 中位置并打印出来 include stdio h include stdlib h ifndef NULL define NULL 0 endif char find char char const source stdlib h stdio h

大家好,我是讯享网,很高兴认识大家。

c和指针的一个6.1习题:在字符串str中字符,查找在字符串source中位置并打印出来。

#include <stdio.h> #include <stdlib.h> #ifndef NULL #define NULL 0 #endif char *find_char ( char const *source, char const *chare) { char *ret; ret = NULL; if (*source == '\0' || *chare == '\0') { return ret; } char temp; char const *p; p = NULL; while((temp = *chare++) != '\0') { /*遍历chare字符串*/ p = source; while(*p != '\0') { if (*p = temp) { return p; /*警告:把char const类型赋值给了char类型了*/ else p++; } } return ret; } int main () { char const *chare = "XYZ"; char const *source = "ABCDEF"; char *result; result = find_char( &source, &chare); if (result == NULL) printf("Not find\n"); else printf("Find %c\n", *result); return 0; } 

讯享网

 

编译报警告:把char const的字符赋值给了char类型,有可能会发生修改错误。


讯享网

不知道怎么修改。

这样改就好了。

讯享网#include <stdio.h> #include <stdlib.h> #ifndef NULL #define NULL 0 #endif char const *find_char ( char const *source, char const *chare) { char *ret = NULL; if (*source == '\0' || *chare == '\0') { return ret; } char temp; char const *p; p = NULL; while((temp = *chare++) != '\0') { /*遍历chare字符串*/ p = source; while(*p != '\0') { if (*p = temp) { return p; /*去掉了:警告:把char const类型赋值给了char类型了*/ else p++; } } return ret; } int main () { char const *chare = "XYZ"; char const *source = "ABCDEF"; char const *result = find_char( &source, &chare); if (result == NULL) printf("Not find\n"); else printf("Find %c\n", *result); return 0; } 

 

小讯
上一篇 2025-04-08 23:11
下一篇 2025-04-11 21:42

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/91576.html