标签:http os ar 代码 on c amp ef 算法
我们思考下算法,然后设计函数。假设主串 s1=nowamagic.net,子串sub=magic。我们要寻找sub在s1中的首个出现位置。
/* 返回子串T在主串S中第pos个字符之后的位置。若不存在,则函数返回值为0。 */
/* 其中,T非空,1≤pos≤StrLength(S)。 */
int Index(String S, String T, int pos)
{
int i = pos; /* i用于主串S中当前位置下标值,若pos不为1,则从pos位置开始匹配 */
int j = 1; /* j用于子串T中当前位置下标值 */
while (i <= S[0] && j <= T[0]) /* 若i小于S的长度并且j小于T的长度时,循环继续 */
{
if (S[i] == T[j]) /* 两字母相等则继续 */
{
++i;
++j;
}
else /* 指针后退重新开始匹配 */
{
i = i-j+2; /* i退回到上次匹配首位的下一位 */
j = 1; /* j退回到子串T的首位 */
}
}
if (j > T[0])
return i-T[0];
else
return 0;
}
测试执行代码为:
case 6:
printf("主串s1为: ");
StrPrint(s1);
k=StrAssign(sub,"magic");
printf("子串sub为: ");
StrPrint(sub);
i=Index(s1,sub,1);
printf("s1的第%d个字母起和sub第一次匹配\n",i);
break;
程序运行结果:
1.StrAssign 生成串 2.StrLength 求串长 3.StrCompare 串比较 4.Concat 串连接 5.SubString 求子串 6.Index 求子串位置 0.退出 请选择你的操作: 1 串s1为:nowamagic.net 6 主串s1为: nowamagic.net 子串sub为: magic s1的第5个字母起和sub第一次匹配
完整的程序在后面部分会给出,就不必每篇都贴了。
标签:http os ar 代码 on c amp ef 算法
原文地址:http://www.cnblogs.com/laoyangman/p/3980740.html