1. 程式人生 > >數據結構(嚴版)課本代碼重敲——第四章

數據結構(嚴版)課本代碼重敲——第四章

all col 除了 如果 free null span maxsize 課本

復習筆記 數據結構 第四章 串

  1 #include <iostream>
  2 #include <string.h>
  3 #include <stdio.h>
  4 #include <stdlib.h>
  5 #define maxSize 20
  6 #define ERROR -1
  7 using namespace std;
  8 /*
  9     題目:數據結構 cha4 串
 10     內容:1. 賦值、取串長度、串比較、串連接、求子串
 11     日期:2018/3/11
12 時間:tomato * 13 14 */ 15 // 定長順序存儲 16 typedef struct 17 { 18 char data[maxSize]; 19 int length; 20 }str1; 21 22 typedef struct 23 { 24 char *ch; 25 int length; 26 }Str; 27 28 // 串比較 29 int cmp(Str s1,Str s2) 30 { 31 for (int i=0; i<s1.length && i<s2.length ;i++)
32 { 33 if (s1.ch[i] != s2.ch[i]) 34 return s1.ch[i] - s2.ch[i]; 35 } 36 return s1.length - s2.length; 37 } 38 // 串賦值 39 int strassign(Str &str,char *ch) 40 { 41 if (str.ch) 42 free(ch);// 如果str中存儲著一個字符串則釋放 43 // 1. 判斷ch的長度,若為0則不用賦值,否則賦值
44 int i = 1; 45 int len_ch=0; 46 while (ch[i]!=\0) 47 { 48 len_ch ++; 49 i++; 50 } 51 if (len_ch == 0) // 空字符串,返回空串 52 { 53 str.length = 0; 54 str.ch = NULL; 55 return 1; 56 } 57 // 否則創建str的結點 58 str.ch = (char *)malloc((len_ch+1)*sizeof(char)); 59 if (str.ch == NULL) 60 return 0; // malloc 失敗!經常被忽略★★★ 61 for (int i=0;i<=len_ch;i++) 62 { 63 str.ch[i] = ch[i]; // 記得最後的\0終止符也要賦值 64 // 除了用數組的方式獲取ch中的值外,還可以 65 // char *c = ch ; 66 // c++ *c即為ch[i]的值 67 } 68 str.length = len_ch ; // ★★★ 長度的賦值經常忘! 69 return 1; 70 } 71 // 串連接 72 int strconcat(Str &str,Str str1,Str str2) 73 { 74 75 int len = str1.length + str2.length ; 76 if (str.ch) 77 free(str1.ch); 78 str.ch = (char *)malloc(sizeof(char)*(len+1)); 79 int i=0; 80 while (str1.length -- ) 81 { 82 str.ch[i] = str1.ch[i];i++; 83 } 84 int j=0; 85 while (str2.length --) 86 { 87 str.ch[i+j] = str2.ch[j];j++; 88 } 89 str.ch[i+j+1] = \0; 90 str.length = str1.length + str2.length; 91 return 1; 92 } 93 // 求子串 94 int substring(Str &substr,Str str,int pos,int len) 95 { 96 if (pos < 0 || pos >str.length || len <0 || len > str.length-pos) 97 return 0; 98 if (substr.ch) 99 free(substr.ch); 100 if (len == 0) 101 { 102 substr.ch = NULL; 103 substr.length = 0; 104 return 1; 105 } 106 substr.ch = (char *)malloc(sizeof(char)*len); 107 int i=0; 108 while (len--) 109 { 110 substr.ch[i] = str.ch[pos]; 111 i++;pos++; 112 } 113 substr.ch[i] = \0; 114 substr.length = len; 115 return 1; 116 } 117 int main() 118 { 119 120 return 0; 121 }

數據結構(嚴版)課本代碼重敲——第四章