HNCU 1746: 算法4-1,4-3:定位子串

题目描述
将子串在母串中第一次出现的位置找出来。

这里写图片描述

图1:在母串中第pos个位置定位子串的算法

这里写图片描述
图2:从母串中第pos个位置获得长度为len的子串

输入
若干对字符串,每对字符串占一行并用一个空格分开。前一个字符串为母串,后者为子串。字符串只包含英文字母的大小写。每个字符串不超过98个字符。

输出
输出子串在母串中首次出现的位置,如果母串中不包含子串则输出0。每个整数占一行。

样例输入
ACMCLUB ACM
DataStructure data
domybest my
样例输出
1
0
3

未完 待续。。。。。。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100
#define ERROR 0
#define OK 1
#define MAX 100

typedef struct{
    char *ch;
    int length;
}String;

int StrLength(String *s)
{
    return s->length ;
}

int StrCompare(String *S,String *T)
{
    int i = 0;
    while(S->ch[i]!=''&&T->ch[i]!='')
    {
        if(S->ch[i]!=T->ch[i])
            return -1;
        i++;
    }
    return 0;
}

int SubString(String *S,String *Sub,int len,int pos)
{
    //用Sub返回串S的第pos个字符起长度为len的子串 
    int i = 0;
    if(pos<0||pos > S->length +1||len< 0||len>S->length)
        return ERROR;
    if(Sub->ch)
        free(Sub->ch);//释放旧空间 
    if(!len)
    {
        Sub->ch = NULL;//空子串 
        Sub->length = 0;
    }
    else
    {//完整子串 
        Sub->ch = (char*)malloc(len*sizeof(char));
        pos-=1;
        while(i < len)
        {
            Sub->ch[i++] = S->ch[pos++];
        }
        if(S->ch[pos-1]!='')
            Sub->ch[i] = '';
        Sub->length = len;
    }
    return OK;
}

int Index(String *S,String *T,int pos)
{
    //T为非空串。若主串S中第pos个字符之后存在与T相等的子串
    //则返回第一个这样的子串在S中的位置,否则返回-1 
    int i = pos;
    int m,n;
    String sub;
    n = StrLength(S);
    m = StrLength(T);
    while( i <= n-m+1)
    {
        SubString(S,&sub,m,i);
        if(StrCompare(&sub,T)!=0)
        {
            i++;
        }
        else
            return i;//返回子串在主串中的位置 
    }
    return -1;//S中不存在与T相等的子串 
}

int main()
{
    String S,T;
    int dex,i,l1,l2;
    char str1[MAX+10],str2[MAX+10];

    while(scanf("%s",str1)!=EOF)
    {
        memset(str2,0,sizeof(str2));
        scanf("%s",str2);
        l1 = strlen(str1);
        l2 = strlen(str2);
        S.ch = (char*)malloc(l1*sizeof(char));
        T.ch = (char*)malloc(l2*sizeof(char));
        S.ch = str1;
        T.ch = str2;
        S.length = l1;
        T.length = l2;
        dex = 1;
        i = Index(&S,&T,dex);
        if(i!= -1)
            printf("%d
",i);
        else
            printf("ERROR
");
    }
    return 0;
 } 
原文地址:https://www.cnblogs.com/hellocheng/p/7350134.html