查找主串中是否还有子串,如果有则返回匹配的第一个位置
题目:
查找主串中是否还有子串,如果有则返回匹配的第一个位置,否则返回-1
#include <stdio.h> #include <string.h> int Index(char *origine, char *target) { if (origine ==NULL||target == NULL) //先检查是否为空 { printf("there is a false\n"); return -1; } int origStrLen = strlen(origine); int targetLen = strlen(target); int pos = -1; int prePos = pos; int i = 0; int j = 0; while(i < origStrLen && j < targetLen) // i,j都从0开始,故是<而不是<= { if (origine[i] == target[j]) { ++i; ++j; } else { i = i - j + 1; //i退回到上次匹配首位的下一位 j = 0; //每次从头开始从新查找子串 } } if (j == targetLen) //判断j是否等于targetLen,如果是则可以获取位置 { prePos = pos; pos = i - j; //获取第一个匹配的位置 } return pos+1; //因为数组从0开始,所以要加1 } int main() { if(Index("hello aaaaa", "aa")) //注意这里的调用要和下面的参数要一致 printf("子串在主串中,并且第一个匹配的字母在主串第%d位置\n",Index("hello aaaaa", "aa")); else printf("子串不在主串中\n"); return 0; }
执行结果:
如果调用的是Index("hello aaaaa", "aA"),或其他不匹配的子串,则打印子串不在主串中,这里不演示了。
posted on 2013-10-11 14:34 love so much 阅读(501) 评论(0) 编辑 收藏 举报
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步