数据结构(严版)课本代码重敲——第四章

复习笔记 数据结构 第四章 串

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define maxSize 20
#define ERROR -1
using namespace std;
/*
    题目:数据结构 cha4 串
    内容:1. 赋值、取串长度、串比较、串连接、求子串
    日期:2018/3/11
    时间:tomato *

*/
// 定长顺序存储
typedef struct
{
    char data[maxSize];
    int length;
}str1;

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

// 串比较
int cmp(Str s1,Str s2)
{
    for (int i=0; i<s1.length && i<s2.length ;i++)
    {
        if (s1.ch[i] != s2.ch[i])
            return s1.ch[i] - s2.ch[i];
    }
    return s1.length - s2.length;
}
// 串赋值
int strassign(Str &str,char *ch)
{
    if (str.ch)
        free(ch);// 如果str中存储着一个字符串则释放
    // 1. 判断ch的长度,若为0则不用赋值,否则赋值
    int i = 1;
    int len_ch=0;
    while (ch[i]!='\0')
    {
        len_ch ++;
        i++;
    }
    if (len_ch == 0) // 空字符串,返回空串
    {
        str.length = 0;
        str.ch = NULL;
        return 1;
    }
    // 否则创建str的结点
    str.ch = (char *)malloc((len_ch+1)*sizeof(char));
    if (str.ch == NULL)
        return 0; // malloc 失败!经常被忽略★★★
    for (int i=0;i<=len_ch;i++)
    {
        str.ch[i] = ch[i]; // 记得最后的\0终止符也要赋值
         // 除了用数组的方式获取ch中的值外,还可以 
         // char *c = ch ; 
         // c++ *c即为ch[i]的值
    }
    str.length = len_ch ; // ★★★ 长度的赋值经常忘!
    return 1;
}
// 串连接
int strconcat(Str &str,Str str1,Str str2)
{
 
    int len = str1.length + str2.length ;
    if (str.ch)
        free(str1.ch);
    str.ch  = (char *)malloc(sizeof(char)*(len+1));
    int i=0;
    while (str1.length -- )
    {
        str.ch[i] = str1.ch[i];i++;
    }
    int j=0;
    while (str2.length --)
    {
        str.ch[i+j] = str2.ch[j];j++;
    }
    str.ch[i+j+1] = '\0';
    str.length = str1.length + str2.length;
    return 1;
}
// 求子串
int substring(Str &substr,Str str,int pos,int len)
{
    if (pos < 0 || pos >str.length || len <0 || len > str.length-pos)
        return 0;
    if (substr.ch)
        free(substr.ch);
    if (len == 0)
    {
        substr.ch = NULL;
        substr.length = 0;
        return 1;
    }
    substr.ch = (char *)malloc(sizeof(char)*len);
    int i=0;
    while (len--)
    {
        substr.ch[i] = str.ch[pos];
        i++;pos++;
    }
    substr.ch[i] = '\0';
    substr.length = len;
    return 1;
}
int main()
{

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值