串在程序中是不可或缺的。char a[]="abcd",就是一个字符串。学习串的目的就是为了对串进行操作。
不过,编译器已经有专门的库来对串进行操作了。所以,我们可以利用这些库,就不要造轮子了。我们学习了串,也就可以自己试着造个轮子来处理串啦!
回到正题。串有三种表达方式:定长顺序储存,堆分配储存,块链储存。这里,只讲堆分配。堆分配储存结构的串既有顺序储存结构的特点,处理方便,操作中对串长有没有任何限制,更显灵活,因此在串处理应用中也常被使用。
#include<iostream> using namespace std; typedef char Elemtype; typedef struct HString { Elemtype *str; int length; }HString; void StrAssign(HString &s,char *string) { //生成串 int len = 0; char *p = string; for (p; *p != '\0'; ++p)++len; s.str = (Elemtype *)malloc(len * sizeof(Elemtype)); int i = 0; while (i < len ) { s.str[i] = *string; ++string; ++i; } s.str[i] = 0; s.length = len; } int StrCompare(HString s1, HString s2) { //比较串 for (int i=0; i < s1.length&&i < s2.length; ++i) if (s1.str[i] != s2.str[i]) return s1.str[i] - s2.str[i]; return s1.length - s2.length; } void Clear_String(HString &s) { //清空串s if (s.str) { free(s.str); s.str = NULL; } s.length = 0; } void Concat(HString &c, HString a, HString b) { //a和b联结成c c.length = b.length + a.length; c.str = (Elemtype *)malloc((c.length + 1) * sizeof(Elemtype)); int i = 0; while (i < c.length ) { if (i < a.length ) c.str[i] = a.str[i]; else c.str[i] = b.str[i - a.length]; ++i; } c.str[i] = 0; } HString SubString(HString s, int pos, int len) { //返回串s的第pos个字符起长度为len的子串 HString son; son.length = len; son.str = (Elemtype *)malloc((len + 1) * sizeof(Elemtype)); Elemtype *p; p = s.str + (pos - 1); int i = 0; while (i < len ) { son.str[i] = *p; ++p; ++i; } son.str[i] = 0; return son; } void test() { HString s1, s2, s3,son; char str1[10], str2[10]; cout << "请输入一串字符给s1:"; cin >> str1; cout << "请输入一串字符给s2:"; cin >> str2; StrAssign(s1, str1); StrAssign(s2, str2); int comp = StrCompare(s1, s2); if (comp > 0)cout << "s1比s2长" << endl; else if (comp < 0)cout << "s1比s2短" << endl; else cout << "一样长" << endl; Concat(s3, s1, s2); cout << s3.str << endl; son = SubString(s3, 3, 5); cout << son.str << endl; } void main() { test(); system("pause"); }
![]()
堆分配储存结构的串
最新推荐文章于 2021-08-11 18:22:26 发布