1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include<stdio.h> #include<string.h> #define MAXLEN 255 typedef struct { char ch[MAXLEN]; int length; }SString; bool StrAssing(SString *T, char ch[]); bool SubString(SString *sub, SString S, int pos, int len); int StrCompare(SString S, SString T); int StrLength(SString T); int Index(SString S, SString T); int main(void) { SString S, sub; char ch[] = "This is String Demo Code"; StrAssing(&S, ch); SubString(&sub, S, 2, 5); printf("sub=%s\n", sub.ch); int len = StrCompare(S, sub); printf("len=%d\n", len); int index = Index(S, sub); printf("index=%d\n", index); return 0; }
bool StrAssing(SString *T, char str[]) { memset(T->ch, 0, MAXLEN); T->length = 0; strcpy(T->ch, str); T->length = (int)strlen(str); printf("len=%d\n",strlen(T->ch)); }
bool SubString(SString *sub, SString S, int pos, int len) { if (pos + len - 1 > S.length) { return false; } memset(sub->ch, 0, MAXLEN); sub->length = 0; strncpy(sub->ch, S.ch + pos, len); sub->length=len; return true; }
bool subString(SString &sub, SString S, int pos, int len) { if (pos + len - 1 > S.length) { return false; } for (int i = pos; i < pos + len; i++) { sub.ch[i-pos+1] = S.ch[i]; } sub.length = len; return true; }
int StrCompare(SString S, SString T) { for (int i = 1; i <= S.length && i <= T.length; i++) { if (S.ch[i] != T.ch[i]) { return S.ch[i] - T.ch[i]; } } return S.length - T.length; }
int Index(SString S, SString T) { int i = 1, n = StrLength(S), m = StrLength(T); SString sub; while (i <= n-m+1) { SubString(&sub, S, i, m); if (StrCompare(sub,T) != 0) { ++i; } else { return i; } } return 0; }
int StrLength(SString T) { return T.length; }
|