串的基本操作

#include<stdio.h>
#include<stdlib.h>

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

void StrAssign(Str *s, char *t);    //字符串初始化
int StrCmp(Str *s1, Str *s2);       //串的比较
void StrCat(Str *s, Str *s1, Str *s2);      //串的连接
void SubString(Str *subStr, Str *str, int pos, int len);    //求子串
int BF(Str *str, Str *subStr);  //求子串的位置

void StrAssign(Str *s, char *t){

    //s如果为空,直接返回。
    if(!s) return;
    //清空原字符串。
    if(s->ch){
        free(s->ch);
        s->ch = NULL;
        s->length = 0;
    }
    //求t串长度
    int tLen = 0;
    char *tmp = t;
    while(*tmp){
        tLen++;
        tmp++;
    }
    //
    if(tLen == 0){
        s->ch = NULL;
        s->length = 0;
    }
    else{
        s->ch = (char*)malloc(sizeof(char) * (tLen + 1));
        s->length = tLen;

        //赋值
        int i = 0;
        tmp = t;
        for(; i <= tLen; i++)
            s->ch[i] = tmp[i];
    }
}

int StrCmp(Str *s1, Str *s2){

    for(; *s1->ch == *s2->ch; s1->ch++, s2->ch++)
        if(*s1->ch == '\0')
            return 0;
    return *s1->ch - *s2->ch;
}

void StrCat(Str *s, Str *s1, Str *s2){

    if(!s) return;

    if(s->ch){
        free(s->ch);
        s->ch = NULL;
        s->length = 0;
    }

    s->ch = (char*)malloc(sizeof(char) * (s1->length + s2->length + 1));
    s->length = s1->length + s2->length;
    int i = 0;
    while(i < s1->length){
        s->ch[i] = s1->ch[i];
        i++;
    }
//    int j = 0;
//    while(j <= s2->length){
//        s->ch[i++] = s2->ch[j++];
//    }
    while(s->ch[i++] = *s2->ch++)
        ;
}

void SubString(Str *subStr, Str *str, int pos, int len){

    if(pos < 0 || pos >= str->length || len < 0 || len > str->length - pos)
        return;
    if(subStr->ch){
        free(subStr->ch);
        subStr->ch = NULL;
        subStr->length = 0;
    }

    if(len == 0){
        subStr->ch = NULL;
        subStr->length = 0;
    }
    else
    {
        subStr->ch = (char*)malloc(sizeof(char) * (len + 1));
        subStr->length = len;

        int i = 0;
        for(; i < len; i++)
            subStr->ch[i] = str->ch[pos + i];
        subStr->ch[i] = '\0';
    }
}

int BF(Str *str, Str *subStr){

    int i = 0, j = 0;
    while(i < str->length && j < subStr->length){

        if(str->ch[i] == subStr->ch[j]){
            i++;
            j++;
        }
        else
        {
            i = i - j + 1;
            j = 0;
        }
    }

    if(j >= subStr->length)
        return i - subStr->length;
    return -1;
}

猜你喜欢

转载自blog.csdn.net/hang981601026/article/details/82930730