1 //定长顺序存储表示 2 /* 3 #include<stdio.h> 4 #include<stdlib.h> 5 #include<string.h> 6 #define TRUE 1 7 #define FALSE 0 8 #define OK 1 9 #define ERROR 0 10 #define INFEASIBLE -1 11 #define OVERFLOW -2 12 #define MAXSTRLEN 255 //可在255以内定义最大串长 13 typedef int Status; 14 typedef unsigned char SString[MAXSTRLEN+1]; //0号单元存放串的长度 15 //串赋值 16 Status StrAssign(SString &S,char *chars) 17 { 18 int i; 19 if(strlen(chars)>MAXSTRLEN) 20 return ERROR; 21 else 22 { 23 S[0] = strlen(chars); 24 for(i=1;i<=S[0];i++) 25 S[i] = *(chars+i-1); 26 return OK; 27 } 28 } 29 //求串长 30 int StrLength(SString S) 31 { 32 return S[0]; 33 } 34 //输出字符串 35 void StrPrint(SString S) 36 { 37 int i; 38 for(i=1;i<=S[0];i++) 39 printf("%c",S[i]); 40 printf("\n"); 41 } 42 //求子串 43 Status SubString(SString &Sub,SString S,int pos,int len) 44 {//用Sub返回串S的第pos个字符起长度为len的子串。 45 //其中,1<=pos<=Strlength(S)且0<=len<=StrLength(S)-pos+1。 46 int i; 47 if(pos<1 || pos>S[0] || len<0 || len>S[0]-pos+1) 48 return ERROR; 49 for(i=1;i<=len;i++) 50 Sub[i] = S[pos+i-1]; 51 Sub[0] = len; 52 return OK; 53 } 54 //串连接 55 Status Concat(SString &T,SString S1,SString S2) 56 {//用T返回由S1和S2连接成的新串。若未截断,则返回TRUE,否则返回FALSE. 57 int i; 58 if(S1[0]+S2[0] <= MAXSTRLEN) 59 {//未截断 60 for(i=1;i<=S1[0];i++) 61 T[i] = S1[i]; 62 for(i=1;i<=S2[0];i++) 63 T[S1[0]+i] = S2[i]; 64 T[0]=S1[0]+S2[0]; 65 return TRUE; 66 } 67 else 68 {//截断 69 for(i=1;i<S1[0];i++) 70 T[i] = S1[i]; 71 for(i=1;i<=MAXSTRLEN-S1[0];i++) 72 T[S1[0]+i] = S2[i]; 73 T[0] = MAXSTRLEN; 74 return FALSE; 75 } 76 } 77 //串比较 78 Status StrCompare(SString S,SString T) 79 {//若S>T,则返回值>0;若S=T,则返回值=0;若S<T,则返回值<0。 80 int i; 81 for(i=1;i<=S[0]&&i<=T[0];++i) 82 if(S[i]!=T[i]) 83 return S[i] - T[i]; 84 else 85 return S[0] - T[0]; 86 } 87 int main() 88 { 89 int i,j,opp=1; 90 char s; 91 SString t,s1,s2,sub; 92 Status k; 93 printf("\n1,StrAssign 生成串\n2,StrLength 求串长\n3,串比较\n"); 94 printf("4,Concat 串连接\n5,SubString 求子串\n"); 95 printf("0,退出\n请选择你的操作:\n"); 96 97 while(opp!=0) 98 { 99 scanf("%d",&opp); 100 switch(opp) 101 { 102 case 1: 103 k=StrAssign(s1,"DOorDIE"); 104 if(!k) 105 { 106 printf("串长超过MAXSTRLEN(=%d)\n",MAXSTRLEN); 107 exit(0); 108 } 109 printf("串s1为:"); 110 StrPrint(s1); 111 printf("\n"); 112 break; 113 case 2: 114 printf("串长为%d\n",StrLength(s1)); 115 break; 116 case 3: 117 k = StrAssign(s2," YOUCAN"); 118 if(!k) 119 { 120 printf("串长超过MAXSTRLEN(=%d)\n",MAXSTRLEN); 121 exit(0); 122 } 123 printf("串s2为:"); 124 StrPrint(s2); 125 printf("\n"); 126 i = StrCompare(s1,s2); 127 if(i<0) 128 s='<'; 129 else if(i==0) 130 s='='; 131 else 132 s='>'; 133 printf("串s1%c串s2\n",s); 134 break; 135 case 4: 136 Concat(t,s1,s2); 137 StrPrint(t); 138 break; 139 case 5: 140 printf("求串s1的子串,请输入子串的起始位置:"); 141 scanf("%d",&i); 142 printf("请输入子串的长度:"); 143 scanf("%d",&j); 144 printf("起始位置:%d,子串长度:%d",i,j); 145 k = SubString(sub,s1,i,j); 146 if(k) 147 { 148 printf("子串sub为:"); 149 StrPrint(sub); 150 } 151 break; 152 case 0: 153 exit(0); 154 } 155 } 156 }*/