一天一个c语言数据结构与算法实现----串

/*四、串*/
/**1.定义*/
typedef struct {
    char *ch;
    int length;
}HString;

/*2.操作*/
void StrAssign(HString *H, char *chars){
    H->ch = chars;
    H->length = strlen(chars);
}

int StrCompare(HString H1, HString H2){
    int minlength = H1.length < H2.length ? H1.length : H2.length;
    int i = 0;
    for (i = 0; i < minlength; i++){
        if (H1.ch[i] < H2.ch[i]){
            return -1;
            break;
        }
        else if (H1.ch[i] > H2.ch[i]){
            return 1;
            break;
        }
        else{
            continue;
        }
    }

    if (H1.length > H2.length)
    {
        return 1;
    }
    else if (H1.length < H2.length)
    {
        return -1;
    }
    return 0;
}


int StrLength(HString H){
    return H.length;
}

HString *Concat(HString H1, HString H2){
    HString *result;
    result = (HString *)malloc(sizeof(HString));
    result->ch = (char *)malloc((H1.length + H2.length + 1) * sizeof(char));
    strcpy(result->ch, H1.ch);
    strcat(result->ch, H2.ch);
    result->length = H1.length + H2.length;
    return result;
}

HString *SubString(HString H, int pos, int len){
    HString *result;
    result = (HString *)malloc(sizeof(HString));
    result->ch = (char *)malloc((len + 1) * sizeof(char));
    strncpy(result->ch, H.ch + pos - 1, len);//strncpy函数用于复制字符串的一部分。与 strcpy 不同,strncpy 可以复制字符串的一部分,而不是整个字符串。
    result->ch[len] = '\0';
    result->length = len;
    return result;
}

void ClearString(HString *H){
    free(H->ch);
    H->length = 0;
    H->ch = NULL;
}

void DestroyString(HString *H){
    free(H->ch);
    free(H);
    H = NULL;
}

bool StrEmpty(HString H){
    if (H.length == 0)
    {
        return true;
    }
    return false;
}


int IndexOf(HString H1, HString H2){
  
    if (StrEmpty(H1) || StrEmpty(H2))
    {
        return -1;
    }
    if(H2.length > H1.length) return -1;
    HString *temp;
   
    for (int i = 0; i <= H1.length - H2.length; i++)
    {
        temp = SubString(H1, i + 1, H2.length);
        if(StrCompare(*temp, H2)== 0) {
            DestroyString(temp);
            return i+1;
        }
    }
    DestroyString(temp);
    return 0;
}

//测试
int main(){

    HString *H1 = (HString *)malloc(sizeof(HString));
    HString *H2 = (HString *)malloc(sizeof(HString));
    StrAssign(H1, "abcdefg");
    StrAssign(H2, "bcd");
    printf("%s\n",H1->ch);
    printf("%s\n",H2->ch);
    printf("%d\n",H1->length);
    printf("%d\n",H2->length);
    printf("%d\n",StrEmpty(*H1));
    printf("%d\n",StrEmpty(*H2));
    printf("%d\n",IndexOf(*H1,*H2));
    HString *H3=Concat(*H1,*H2);
    printf("%s\n",H3->ch);
    StrAssign(H1, H2->ch);
    printf("%s\n",H1->ch);
    DestroyString(H2);
    DestroyString(H1);
    DestroyString(H3);
    return 0;
}

你可能感兴趣的:(C语言数据结构与算法,c语言,算法,数据结构)