#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Max 100
#define TRUE 1
#define FALSE 0
typedef unsigned char SString[Max+1];
typedef int Status;
Status StrAssign(SString T,char *strs)
{ // 生成一个其值等于chars的串T
int i;
T[0]=0;
for(i=0;strs[i];i++)
{
T[i+1]=strs[i];
T[0]=i+1;
}
}
int Index(SString S,SString T,int pos)
{ // 返回子串T在主串S中第pos个字符之后的位置。若不存在,则函数值为0。
// 其中,T非空,1≤pos≤StrLength(S)。算法4.5
int i,j;
i = pos;
j = 1;
while( i<=S[0] && j<=T[0] )
{
if(S[i]==T[j])
{
++i;
++j;
}
else
{
i=i-j+2;
j=1;
}
}
if(j>T[0])
return i-T[0];
else
return 0;
}
int main()
{
SString S,T;
int m;
char strs1[Max];
char strs2[Max];
printf("输入主串:");
gets(strs1);
printf("输入子串:");
gets(strs2);
StrAssign(S,strs1);
StrAssign(T,strs2);
m=Index(S,T,1);
if(m)
printf("%d\n",m);
else
printf("0\n");
return 0;
}
C语言数据结构——子串在主串中的定位函数
最新推荐文章于 2024-06-26 16:37:16 发布
本文详细介绍了如何使用C语言编写一个函数,该函数用于在主字符串中查找并定位子字符串的位置。通过遍历和比较字符,实现高效的查找算法,为数据结构的学习者提供实践指导。


4277

被折叠的 条评论
为什么被折叠?



