c语言字符串的模式匹配和c++string的一般操作

#include <stdio.h>
 #include"common.h"

#define OK 0
#define ERROR 1


/*
 * 字符串模式匹配
 * */

//字符结构体

typedef struct
{
    
    
 char data[Maxsize];
 int length;
}SqString;

//暴力破解法,时间复杂度n平方
int BF_Index(SqString s, SqString t)
{
    
    
    int i=0,j=0;
    while(i<s.length && j<t.length)
        {
    
    
       if(s.data[i]==t.data[j])
           {
    
    
                i++,j++;
           }
       else
           {
    
    
                 i=i-j+1;   //i-j回到开始位置 +1 的下一位
                 j=0;
           }
    }
    if(j>=t.length)
        return(i-t.length);
    else
        return(-1);

}

void GetNextval(SqString t,char nextval[])
{
    
    
    int j =0, k =-1;
    next[0] = -1;
    while(j<t.length)
        {
    
    
        if(k==-1 || t.data[k]==t.data[j])
            {
    
    
            j++;k++;
            if(t.data[k]!=t.data[j])
                nextval[j] = k;
            else
                nextval[j] = nextval[k];

        }
        else
            k = nextval[k];


    }

}

int KMP_Index(SqString s, SqString t)
{
    
    
    int nextval[MaxSize], i=0, j=0;
    GetNextval(t,nextval);       //获取j的后退值
    while(i<s.length && j<t.length)
        {
    
    
        if(j==-1 || s.data[i]==t.data[j])
            {
    
    
            i++;
            j++;
        }
        else
            j = nextval[j];      //i不后退,j不一定回溯到0
    }
    if(j>=t.length)
        return(i-t.length);
    else
        return(-1);
}

//空串 ""   表示一个空字符串,长度为0。

//空格串 " "  表示一个空格

//c++中字符串的一些函数

strcpy(s1,s2);      //复制字符串s2到字符串s1
strcat(s1,s2);      //连接字符串s2到字符串s1的尾部
strlen(s1);         //返回字符串s1的长度
strcmp(s1,s2);      //返回字符串s1和s2的比较结果
strcasecmp(s1,s2);  //忽略大小比较
strchr(s1,ch);      //返回指向字符串s1中第一个ch的指针
strstr(s1,s2);      //返回指向字符串s1中第一个字符串s2的指针

find();             //从头开始找
rfind();            //从尾部开始找

//读取方式
str[i];
str.at(i);

insert();               //插入
erase();                //删除

猜你喜欢

转载自blog.csdn.net/weixin_50188452/article/details/110673855