1 #include <iostream>
2 #include <string.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #define maxSize 20
6 #define ERROR -1
7 using namespace std;
8 /*
9 题目:数据结构 cha4 串
10 内容:1. 赋值、取串长度、串比较、串连接、求子串
11 日期:2018/3/11
12 时间:tomato *
13
14 */
15 // 定长顺序存储
16 typedef struct
17 {
18 char data[maxSize];
19 int length;
20 }str1;
21
22 typedef struct
23 {
24 char *ch;
25 int length;
26 }Str;
27
28 // 串比较
29 int cmp(Str s1,Str s2)
30 {
31 for (int i=0; i<s1.length && i<s2.length ;i++)
32 {
33 if (s1.ch[i] != s2.ch[i])
34 return s1.ch[i] - s2.ch[i];
35 }
36 return s1.length - s2.length;
37 }
38 // 串赋值
39 int strassign(Str &str,char *ch)
40 {
41 if (str.ch)
42 free(ch);// 如果str中存储着一个字符串则释放
43 // 1. 判断ch的长度,若为0则不用赋值,否则赋值
44 int i = 1;
45 int len_ch=0;
46 while (ch[i]!='\0')
47 {
48 len_ch ++;
49 i++;
50 }
51 if (len_ch == 0) // 空字符串,返回空串
52 {
53 str.length = 0;
54 str.ch = NULL;
55 return 1;
56 }
57 // 否则创建str的结点
58 str.ch = (char *)malloc((len_ch+1)*sizeof(char));
59 if (str.ch == NULL)
60 return 0; // malloc 失败!经常被忽略★★★
61 for (int i=0;i<=len_ch;i++)
62 {
63 str.ch[i] = ch[i]; // 记得最后的\0终止符也要赋值
64 // 除了用数组的方式获取ch中的值外,还可以
65 // char *c = ch ;
66 // c++ *c即为ch[i]的值
67 }
68 str.length = len_ch ; // ★★★ 长度的赋值经常忘!
69 return 1;
70 }
71 // 串连接
72 int strconcat(Str &str,Str str1,Str str2)
73 {
74
75 int len = str1.length + str2.length ;
76 if (str.ch)
77 free(str1.ch);
78 str.ch = (char *)malloc(sizeof(char)*(len+1));
79 int i=0;
80 while (str1.length -- )
81 {
82 str.ch[i] = str1.ch[i];i++;
83 }
84 int j=0;
85 while (str2.length --)
86 {
87 str.ch[i+j] = str2.ch[j];j++;
88 }
89 str.ch[i+j+1] = '\0';
90 str.length = str1.length + str2.length;
91 return 1;
92 }
93 // 求子串
94 int substring(Str &substr,Str str,int pos,int len)
95 {
96 if (pos < 0 || pos >str.length || len <0 || len > str.length-pos)
97 return 0;
98 if (substr.ch)
99 free(substr.ch);
100 if (len == 0)
101 {
102 substr.ch = NULL;
103 substr.length = 0;
104 return 1;
105 }
106 substr.ch = (char *)malloc(sizeof(char)*len);
107 int i=0;
108 while (len--)
109 {
110 substr.ch[i] = str.ch[pos];
111 i++;pos++;
112 }
113 substr.ch[i] = '\0';
114 substr.length = len;
115 return 1;
116 }
117 int main()
118 {
119
120 return 0;
121 }