串——是由零个字符或多个字符组成的有限序列。
串的基本操作包括串的初始化,打印串,求长度,串的比较,串的清空,求子串,串的合并,还有搜索定位函数。
1.串的初始化。
1 int StrAssign(SS &T,const char * chars) 2 { 3 int i; 4 for(i = 0;*(chars+i);i++); 5 if(i == 0) 6 { 7 T.ch = NULL; 8 T.length = 0; 9 } 10 else 11 { 12 T.ch = (char *)malloc(i*sizeof(char)); 13 if(!T.ch) 14 { 15 printf("内存分配失败!"); 16 return 0; 17 } 18 else 19 { 20 for(int j = 0;j < i;j++) 21 { 22 *(T.ch+j) = *(chars+j); 23 } 24 T.length = i; 25 } 26 } 27 return 0; 28 }
2.串的打印.
1 int StrPrint(SS &T) 2 { 3 int i; 4 i = T.length; 5 if(i==0) 6 printf("串为空\n"); 7 for(i = 0;i <T.length;i++) 8 { 9 printf("%c",*(T.ch+i)); 10 } 11 return 0; 12 }
3.返回串的长度.
1 int StrLength(SS &S) 2 { 3 return S.length; 4 }
4.串的比较函数.
1 int StrCompare(SS &s,SS &t) 2 { 3 int i; 4 for(i = 0;i < s.length && i < t.length;i++) 5 if(s.ch[i]!=t.ch[i]) 6 return s.ch[i]-t.ch[i]; 7 return s.length-t.length; 8 }
5.串的清空.
1 int StrClear(SS &s) 2 { 3 if(s.ch) 4 { 5 free(s.ch); 6 s.ch = NULL; 7 } 8 s.length = 0; 9 return 0; 10 }
6.求子串函数.
1 int StrSub(SS &s,SS t,int pos,int n) 2 { 3 int i; 4 if(n < 0 || n > t.length ||pos < 1 || pos > t.length-pos+1) 5 { 6 printf("error\n"); 7 return 0; 8 } 9 if(n == 0) 10 { 11 s.ch = NULL; 12 s.length = 0; 13 } 14 else 15 { 16 s.ch = (char *)malloc(n *sizeof(char)); 17 for( i = 0;i < n;i++) 18 { 19 *(s.ch+i) = *(t.ch+pos+i-1); 20 } 21 s.length = n; 22 23 } 24 return 0; 25 }
7.串的合并.
1 int concat(SS &T,SS s1,SS s2) 2 { 3 int i,j; 4 if(T.ch) 5 free(T.ch); 6 if(!(T.ch = (char*)malloc((s1.length + s2.length)*sizeof(char)))) 7 return 0; 8 T.length = s1.length + s2.length; 9 for(i = 0;i < s1.length;i++) 10 *(T.ch+i) = *(s1.ch+i); 11 for(j = 0;j < s2.length;j++) 12 *(T.ch+s1.length+j) = *(s2.ch + j); 13 return 0; 14 15 }
8.搜索函数.
1 int Index(SS s,SS a, int pos) 2 { 3 int n,m,i; 4 SS t; 5 if(pos > 0) 6 { 7 n = s.length; 8 m = a.length; 9 i = pos; 10 while(i <= n-m+1) 11 { 12 StrSub(t,s,i,m); 13 if(StrCompare(t,a)!=0) 14 i++; 15 else 16 return i; 17 18 } 19 } 20 return 0; 21 22 }
以上是各个函数的实现,实现方法可能比较复杂,但是可行。下边附上主函数的检验。
1 int main() 2 { 3 char s[20] = "ABCDEF"; //创建一个数组 4 SS t,a,b; //创建串 5 StrAssign(a,"CD"); //将字符串赋值给串a 6 StrAssign(t,s); //将字符数组赋值给串t 7 StrPrint(t); //打印串t 8 printf("\n%d\n",t.length); //打印串t的长度 9 printf("%d\n",StrCompare(t,a)); //返回比较函数的差值或者长度差值 10 StrSub(b,t,2,2); //求子串,求t的从第2个位置长度为2的子串 11 StrPrint(b); //打印串b 12 StrClear(b); //清空串b 13 StrPrint(b); //打印串b 14 concat(b,t,a); //连接串t,a并生成新的串b 15 StrPrint(b); //打印串b 16 printf("\n%d\n",Index(t,a,1)); //搜索函数,返回t在a中第1个位置后出现的第一个位置 17 return 0; 18 }