#include <stdio.h>
#include <stdlib.h>
#define Num 255
typedef struct String
{
char ch[Num];
int len;
}String;
void StrAssign(String *T,char *s)
{
int i=0;
while(s[i]!='\0')
{
T->ch[i]=s[i];
i++;
}
T->ch[i]='\0';
T->len=i;
}
int StrLength(String T)
{
int i=0;
while(T.ch[i]!='\0') i++;
T.len=i;
return i;
}
void StrCopy(String *T,String *S)
{
int i=0;
while(S->ch[i]!='\0') {T->ch[i]=S->ch[i];i++;}
T->ch[i]='\0';
T->len=i;
}
void ClearString(String *T)
{
int i=0;
T->len=0;
while(T->ch[i]!='\0') T->ch[i++]='\0';
}
void Concat(String *T,String *S,String *M)
{
int i,j;
for(i=0;i<S->len;i++) T->ch[i]=S->ch[i];
for(j=0;j<=M->len;j++) T->ch[i+j]=M->ch[j];
}
int SubString(String *sub,String *S,int pos,int len)
{
if((pos<1||pos>S->len)&&(len<0||len+pos-1>S->len))
return -1;
int i;
for(i=0;i<len;i++)
sub->ch[i]=S->ch[pos+i-1];
sub->ch[i]='\0';
return 1;
}
int Index(String *S,String *T,int pos)
{
int i=pos-1,j=0;
while(i<S->len&&j<T->len)
{
if(S->ch[i]==T->ch[j]){ i++;j++; }
else { i=i-j+1;j=0; }
}
if(j>=T->len) return i-j;
return -1;
}
int main()
{
String T,M,S,N;
char *p="wqhsucclipingwangzijian";
char *q="lipingwang";
printf("串的基本操作:\n");
StrAssign(&T,p);
printf("1 串的常量复制 T=%s\n",T.ch);
StrCopy(&M,&T);
printf("2 串的复制 M=%s\n",M.ch);
StrAssign(&S,q);
printf("3 串的常量复制 S=%s\n",S.ch);
printf("4 串的匹配 Index(M,S,3)=%d\n",Index(&M,&S,3));
Concat(&M,&T,&S);
printf("5 串T的长度=%d\n",StrLength(T));
SubString(&N,&M,5,6);
printf("6 串的链接SubString(N,M,5,6)=%s\n",N.ch);
ClearString(&M);
ClearString(&T);
ClearString(&N);
printf("7 串已置空!\n");
printf("8 串的操作结束!\n");
return 0;
}