相关知识:
在一个长字符串中寻找一个短字符串出现的位置,这是字符串匹配问题。
/*
从字符串t查找子字符串p。
字符串以数值结尾,例如p="str",那么p[0]='s',p[1]='t',p[2]='r',p[3]=0。
采用朴素的匹配算法,返回子字符串第一次出现的位置,例如t="string ring",p="ring",则返回2。
若没有找到,则返回-1。
*/
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int FindSubStr(char* t, char* p)
{
int k = 0;
int lent = strlen(t);
int lenp = strlen(p);
for(int i = 0;i < lent;i ++)
{
if(t[i]==p[0])
{
int f = i,k = f;
for(int j = 0;j < lenp;j++,f++)
{
if(t[f]!=p[j])
break;
if(j==lenp-1)
{
return k;
}
}
}
}
return -1;
}
int main()
{
// to test finding the first son string
char t[100]; // mother string
char p[100]; // son string
scanf("%s", t);
scanf("%s", p);
int i=FindSubStr(t, p);
printf("Location: ");
if(i==-1) printf("not found!");
else printf("%d",i);
return 0;
}