1. 程式人生 > >【資料結構】4.1串的基本操作(附程式碼實現)

【資料結構】4.1串的基本操作(附程式碼實現)

串的基本操作有:

  1. 賦值
  2. 連線
  3. 比較
  4. 清空
  5. 求子串

具體程式碼如下

#include <stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h> 

typedef struct String{
    char * ch;
    int length;
}Str;

void StrInit(Str &str);//有多個由結構體創造出來的變數時(str1,str2,str3),不初始化很危險! 
int StrAssign(Str &str ,char
* ch) ;//賦值 int GetStrLength(Str str);//獲取長度 int StrCompare(Str s1,Str s2);//比較 int Concat(Str str1, Str str2, Str &str);//連線 int GetSubString(Str str,int pos, int len, Str &substr);//求子串 int ClearString(Str &str); //清空 int main(void) { Str str1, str2, str3,substr; StrInit(str1); StrInit(str2); StrInit(str3); StrInit(substr); char
ch1[] = "I love China!"; char ch2[] = "I love U!"; char ch3[] = "Data structure!"; StrAssign(str1, ch1); StrAssign(str2, ch2); StrAssign(str3, ch3); Concat(str1,str2,str3) ; GetSubString(str3,3,7,substr); printf("%s\n",str1.ch); printf("%s\n",str2.ch); printf("%s\n"
,str3.ch); printf("%s\n",substr.ch); return 0; } void StrInit(Str &str) { str.length = 0; str.ch = NULL; } int StrAssign( Str & str ,char * ch) { //賦值 if(str.ch) //如果str.ch原先有存其他東西,就釋放掉原先的東西 { free(str.ch); str.ch = NULL; } int len = 0; char * c = ch; while (*c) { //求串長 ++len; ++c; } if(len == 0) //空串 { str.ch = NULL; str.length = 0; return 1; } else { str.ch = (char *)malloc(sizeof(char)*(len + 1)); if(str.ch ==NULL)//空間分配失敗 return 0; else {//寫法1 c = ch; for(int i = 0; i <= len ; ++i,++c) str.ch[i] = *c; str.length = len; return 1; } // {//寫法2 // i = 0; // c = ch; // while(c*) // { // str.ch[i] = c*; // ++c; // ++i; // } // str.[++i] = '\0'; // str.length = i; // } } } int GetStrLength(Str str) { return str.length; } int StrCompare(Str str1,Str str2) { //串比較 for(int i = 0; i <str1.length && i < str2.length; ++i) if(str1.ch[i] != str2.ch[i]) return str1.ch[i] - str2.ch[i]; return str1.length - str2.length; } int Concat(Str str1, Str str2, Str &str) { //串連線 if(str.ch) { free(str.ch); str.ch = NULL; } str.ch = (char *)malloc(sizeof(char)*(str1.length + str2.length + 1)); if(!str.ch) //空間分配失敗 return 0; int i = 0,j = 0; while (i <str1.length) { str.ch[i] = str1.ch[i]; ++i; } while(j < str2.length) { str.ch[i + j] = str2.ch[j]; ++j; } str.ch[i+j] = '\0'; str.length = str1.length + str2.length; return 1; } int GetSubString(Str str,int pos, int len, Str &substr) { //求子串:從主串str裡的第pos位置後開始,依次把len個元素作為子串substr if(pos < 0 || pos >=str.length || len < 0 || len > str.length - pos) return 0; if(substr.ch) { free(substr.ch); substr.ch == NULL; } if(len == 0) { substr.ch = NULL; substr.length = 0; return 1; } else { substr.ch = (char*)malloc(sizeof(char) * (len + 1)); int i = pos, j = 0; while(i < pos + len) { substr.ch[j] = str.ch[i]; ++i; ++j; } substr.ch[j] = '\0'; substr.length = len; return 1; } } int ClearString(Str & str) { //清空串 if(str.ch) { free(str.ch); str.ch == NULL; } str.length = 0; return 1; }