C语言----字符串的匹配

字符串的匹配

实例说明:

        本实例实现对两个字符串进行匹配操作,即在第一个字符串中查找是否存在第二个字符串。如果字符串完全匹配,则提示匹配的信息,并显示第二个字符串在第一个字符串中的开始位置,否则提示不匹配。

实现过程:

        (1)在TC中创建一个C文件。

        (2)引用头文件,代码如下:

#include <stdio.h>
#include <string.h>
#include <conio.h>

        (3)自定义函数match(),实现字符串匹配操作。代码如下:

int match(char *B,char *A){
    int i,j,start = 0;
    int lastB = strlen(B) - 1;
     int lastA = strlen(A) - 1;
     int endmatch = lastA;
     for (j = 0; endmatch <= lastB;endmatch++,start++)
     {
        if (B[endmatch] == A[lastA])
            for ( j = 0,i = start; j < lastA && B[i] == A[j]; )
                i++,j++;
        if (j == lastA)
        {
            return (start+1);
        }
           if (endmatch > lastB)
           {
            printf("The string is not matchable!");
            return -1;
           }
     }
}

        (4)创建 main()函数,在此函数中调用 match()函数,将得到的结果输出在窗体上。代码如下:

int main(int argc, char const *argv[])
{
    char s[] = "One world,onr dream";
    char t[] = "world";
    int p = match(s,t);
    if (p != -1)
    {
        printf("Matchable!\n");
        printf("The start position is %d", p);
    }
    printf("\n");
    getch();
    return 0;
}

        (5)完成代码如下:

#include <stdio.h>
#include <string.h>
#include <conio.h>
int match(char *B,char *A){
    int i,j,start = 0;
    int lastB = strlen(B) - 1;
     int lastA = strlen(A) - 1;
     int endmatch = lastA;
     for (j = 0; endmatch <= lastB;endmatch++,start++)
     {
        if (B[endmatch] == A[lastA])
            for ( j = 0,i = start; j < lastA && B[i] == A[j]; )
                i++,j++;
        if (j == lastA)
        {
            return (start+1);
        }
           if (endmatch > lastB)
           {
            printf("The string is not matchable!");
            return -1;
           }
     }
}
int main(int argc, char const *argv[])
{
    char s[] = "One world,onr dream";
    char t[] = "world";
    int p = match(s,t);
    if (p != -1)
    {
        printf("Matchable!\n");
        printf("The start position is %d", p);
    }
    printf("\n");
    getch();
    return 0;
}

运行结果:

       

技术要点:

        本实例创建了自定义函数 matchO进行字符串的匹配操作。matchO)函数包含两个参数参数B为要进行匹配操作的字符串,其类型为字符型指针;参数A为用来匹配的字符串使用循环语句比较A字符串最后一个字符是否与B中字符相同,如果相同,使用循环语句比较A与B是否匹配。

        希望能对您的学习和工作有所帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值