// A heap-based string. # include <stdio. h> # include <string. h> # include <stdlib. h> # include <malloc. h> # define soverflow-1 # define OK 1 # define error 0 typedef int status; typedef struct {char * Ch; int length ;}string; Status strassign (string & S, char * chars) {If (S. ch) {free (S. ch);} int Len = strlen (chars); If (! Len) {S. CH = NULL; S. Length = 0;} else {If (! (S. ch = (char *) malloc (LEN * sizeof (char) {exit (soverflow) ;}for (INT I = 0; I <Len; I ++) {S. ch [I] = chars [I]; S. length = Len ;}} Return OK;} int strlength (string s) {return S. length;} void visitstring (string s) {printf ("s. length: % d ", strlength (s); For (INT I = 0; I <strlength (s); I ++) {printf (" % C ", S. ch [I]);} printf ("\ n");} int strcompare (string S, string t) {for (INT I = 0; I <S. length & I <t. lengt H; I ++) {If (S. ch [I]! = T. ch [I]) {return S. ch [I]-t. ch [I] ;}} return S. length-t. length;} status clearstring (string & S) {If (S. ch) {free (S. ch); S. ch = NULL;} s. length = 0;}/** use the string S1 and string S2 connections to generate a new string T */status Concat (string & T, string S1, string S2) {If (T. ch) {free (T. ch);} int len1 = strlength (S1), len2 = strlength (S2); If (! (T. ch = (char *) malloc (len1 + len2) * sizeof (char) {exit (soverflow) ;}for (INT I = 0; I <len1; I ++) {T. ch [I] = s1.ch [I];} t. length = len1 + len2; For (INT I = len1; I <t. length; I ++) {T. ch [I] = s2.ch [I-len1];} Return OK;}/** use sub to return the substring in string s with the length of Len starting from the POs position. */Status substring (string & sub, string S, int POs, int Len) {If (Pos <1 | POS> strlength (s) | Len <0 | Len> strlength (S)-pos + 1) {return error;} If (sub. ch) {free (sub. ch);} If (! Len) {sub. ch = NULL; sub. length = 0;} else {sub. ch = (char *) malloc (LEN * sizeof (char); For (INT I = 0; I <Len; I ++) {sub. ch [I] = S. ch [POS + I-1];} sub. length = Len;} Return OK;} Main () {string S, T, R, sub; strassign (S, "abcdefg"); strassign (T, "abcdefgeefe "); visitstring (s); visitstring (t); printf ("strcompare: % d \ n", strcompare (S, T); Concat (R, S, T ); visitstring (r); substring (sub, R, 1, 7); visitstring (sub); substring (sub, R, 8, 11); visitstring (sub); System ("pause "); return 0 ;}