(八)串的简单操作(输出串后面出现乱码问题解决)

本文介绍了一种使用堆分配存储结构实现串处理的方法,并提供了初始化、生成、连接等基本操作的C语言实现示例。文章还展示了如何通过具体函数进行串的创建、比较、打印等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

堆分配存储结构的串由顺序存储结构的特点,处理方便。

存储结构:

typedef struct{
    char *ch;
    int length;
}HString;
函数

//初始化
void Str_Init(HString *S){
    S->ch = NULL;
    S->length = 0;
}

//生成一个值等于串常量chars的串T
Status StrAssign(HString *T, char *chars){
    if(T->ch) free(T->ch);
    int i;
    char *c;
    //求chars的长度i
    for(i=0,c=chars; *c; ++i,++c);
    if(!i){
        T->ch = NULL;
        T->length = 0;
    }
    else{
        //给T分配空间
        if(!(T->ch=(char*)malloc(i*sizeof(char))))
            exit(OVERFLOW);
        //把chars赋值给T
        for(int j=0;j<i;j++)
            T->ch[j] = chars[j];
        T->length = i;
    }
    return OK;
}

//返回T的长度
int StrLength(HString T){
    return T.length;
}

//若S>T,则返回值>0;若S=T,则返回=0;若S>0,则返回<0
int StrCompare(HString S,HString T){
    int i;
    for(i=0;i<S.length && i<T.length;++i){
        if(S.ch[i] != T.ch[i])
            return S.ch[i]-T.ch[i];
    }
    return S.length-T.length;
}

//清空串
Status ClearString(HString *S){
    if(S->ch){
        free(S->ch);
        S->ch = NULL;
    }
    S->length = 0;
    return OK;
}

//链接S1和S2形成新的串由T返回
Status Concat(HString *T,HString S1,HString S2){
    int i,j;
    if(T->ch) ClearString(T);
    if(!(T->ch=(char*)malloc(sizeof(char)*(S1.length+S2.length))))
        exit(OVERFLOW);
    for (i = 0; i < S1.length; i++) {
        T->ch[i] = S1.ch[i];
    }
    T->length = S1.length + S2.length;
    for (j = 0; j < S2.length; j++) {
        T->ch[i++] = S2.ch[j];
    }
    T->ch[i]='\0';
    return OK;
}

//判断顺序串是否为空
int Str_IsEmpty(HString *S){
    return S->length == 0;
}

//打印顺序串
void Str_Print(HString *S){
    //int i = 0;
    if(Str_IsEmpty(S)){
        printf("顺序串为空!\n");
        exit(0);
    }
    else//printf("%s\n",S->ch);
    {
        while (putchar(*S->ch++));
        printf("\n");
    }

}

main函数

int main() {

    HString T;
    Str_Init(&T);

    char *chars = "asdf\0";
    StrAssign(&T,chars);
    Str_Print(&T);
    printf("%d\n",T.length);

    HString S1,S2;
    S1.ch = "hello\0";
    S1.length = 5;
    S2.ch = "abc\0";
    S2.length = 3;
    Concat(&T,S1,S2);
    Str_Print(&T);
    printf("%d\n",T.length);

    return 0;
}

打印字符串后面出现乱码原因是由于没有加结束符\0








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值