数据结构 通俗易懂版 c语言描述----串及其基本操作
2022.2.11
串及其基本操作
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <malloc.h> typedef struct Str { char *ch; int length; } Str; //赋值操作 ch的值赋给str->ch eg Strassign(str,"aaaa"); bool Strassign(Str *str, char *ch) { int i = 0, j = 0; char *c = ch; while (*c) { i++; c++; } if (i == 0) { // ch为空串 就直接返回空串 str->ch = ; str->length = 0; return true; } else { str->ch = (char *)malloc(sizeof(char) * (i + 1)); if (str->ch == NULL) return false; c = ch; for (j; j < i; j++) { str->ch[j] = *c; c++; } str->ch[j] = ; str->length = i; return true; } } //比较操作 int StrCompare(Str *s1, Str *s2) { int i = s1->length, j = s2->length; for (int a = 0; a < i && a < j; a++) { if (s1->ch[a] != s2->ch[a]) { return (s1->ch[a]) - (s2->ch[a]); } } // for循环结束 则说明其中一个串已经完了且两个串前面全部相同 此时比串的长度就行 return (s1->length) - (s2->length); } //连接俩个串 bool concat(Str *s, Str *s1, Str *s2) { s->ch = (char *)malloc(sizeof(char) * (s1->length + s2->length + 1)); if (s->ch == NULL) return false; char *c1 = s1->ch; char *c2 = s2->ch; int i = 0; for (i; i < s1->length; i++) { s->ch[i] = *c1; c1++; } for (int j = 0; j < s2->length + 1; j++) { s->ch[i++] = *c2; c2++; } s->length = s1->length + s2->length; return true; } //求子串操作 pos为起始位置 len为子串的总长度 bool Substring(Str *s, Str *r, int pos, int len) { if (pos < 0 || pos > r->length || len < 0 || pos + len > r->length) return false; s->ch = (char *)malloc(sizeof(char) * (len + 1)); int j = 0; if (len == 0) { s->ch = ; s->length = 0; return true; } else { for (int i = pos; i < pos + len; i++, j++) { s->ch[j] = r->ch[i]; } s->ch[j] = ; s->length = len; return true; } } //测试 int main() { Str *p; p = (Str *)malloc(sizeof(Str)); Strassign(p, "mmmm ???m,m-.- "); printf("%s-%d", p->ch, p->length); Str *s, *s1, *s2, *s3; s = (Str *)malloc(sizeof(Str)); s1 = (Str *)malloc(sizeof(Str)); s2 = (Str *)malloc(sizeof(Str)); s3 = (Str *)malloc(sizeof(Str)); s1->ch = "abaa ac ", s1->length = 8; s2->ch = "aaa bbb ccc", s2->length = 11; int a = StrCompare(s1, s2); printf("%d ", a); concat(s, s1, s2); printf("%s-%d ", s->ch, s->length); Substring(s3, s, 2, 5); printf("%s ", s3->ch); }