標籤:列印 struct lib 實現 ssi index 元素 出現 real
#include <stdio.h>#include <tchar.h>#include <stdlib.h>// TODO: 在此處引用程式需要的其他標頭檔struct String{ char* ch; int length;};bool Assign_String(String* str, char* chars);bool Destroy_String(String* str);bool Clear_String(String* str);void Print_String(String str);bool Insert_String(String* str, String T, int locate);bool Copy_String(String* str, String T);int Index_String(String str, String T);//給字串重新賦值bool Assign_String(String* str,char* chars){ if (str->ch) free(str->ch); int i; char* c; for (i = 0, c = chars; *c; c++, i++);//擷取字串長度 if (!i) { str->ch = NULL; str->length = 0; return true; } else{ str->ch = (char*)malloc(i*sizeof(char)); for (int j = 0; j < i; j++){ str->ch[j] = chars[j]; } str->length = i; return true; }}//銷毀字串bool Destroy_String(String* str){ if (str) { free(str); str = NULL; return true; } else return false;}//清Null 字元串bool Clear_String(String* str){ while (str->length){ str->ch[str->length] = NULL; str->length--; } return true;}//列印void Print_String(String str){ if (str.length) { for (int i = 0; i < str.length;i++) { printf("%c", str.ch[i]); } printf("\n"); }}//在原字串str的第locate個元素前插入子字串Tbool Insert_String(String* str, String T, int locate){ if (locate<0 || locate>str->length) return false; if (T.length){ if (!(str->ch = (char*)realloc(str->ch,(str->length + T.length)*sizeof(char)))) exit(-1); for (int i = str->length - 1; i >= locate; i--) str->ch[i + T.length] = str->ch[i]; for (int i = 0; i < T.length; i++) str->ch[locate + i] = T.ch[i]; str->length += T.length; } return true;}//把T的值賦給strbool Copy_String(String* str, String T){ if (str->ch) free(str->ch); if (!&T) { str->ch = NULL; str->length = 0; return true; } else{ str->ch = (char*)malloc(T.length*sizeof(char)); for (int i = 0; i < T.length; i++){ str->ch[i] = T.ch[i]; } str->length = T.length; } return true;}//在原字串str中搜尋子字串T的位置//尋找失敗返回-1//正常返回index為第一次出現T首字元的位置int Index_String(String str, String T){ int index = -1; int key = 0; int Hl = 0; if (T.length&&str.length>=T.length){ for (int i = 0; i <= str.length - T.length; i++){ if (str.ch[i] == T.ch[key]){ key++; Hl++; if (Hl >= T.length) { printf("出來了\n"); index = i - T.length+1; return index; } } else{ Hl = key = 0; } printf("i=%d,str是%c,T是%c,核對T的第%d個字元,已滿足字元數%d\n", i, str.ch[i], T.ch[key], key, Hl); } } return index;}
c語言實現基本的資料結構(六) 串