#include <iostream>
using namespace std;
//串的定长顺序存储表示
#define MAXSIZE 20
typedef char SString [MAXSIZE];
//获取串长strlen()
int strlen(SString s)
{
int i=0;
int counter=0;
while (s[i]!=NULL)
{
counter++;
i++;
}
return i;
}
//串的复制strcpy()
char* strcpy(SString &s1,SString s2)
{
for (int i=0;i<strlen(s2);i++)
{
s1[i]=s2[i];
}
return s1;
}
//获取pos位置起长度为len的子串Substr()
char* Substr(SString &sub,SString str,int pos,int len)
{
if (pos<1||pos>strlen(str)||len<0||len>strlen(str)-pos+1)
{
cout<<"pos或len的数据不合法!"<<endl;
exit(1);
}
for (int i=pos;i<=len+pos-1;i++)
{
sub[i-pos]=str[i];
}
return sub;
}
//串的链接strcat()
char* strcat(SString &t,SString str1,SString str2)
{
if (strlen(str1)+strlen(str2)<=MAXSIZE)
{
for (int i=0;i<strlen(str1);i++)
{
t[i]=str1[i];
}
for (int i=0;i<strlen(str2);i++)
{
t[i+strlen(str1)]=str2[i];
}
}else if (strlen(str1)<MAXSIZE)
{
for (int i=0;i<strlen(str1);i++)
{
t[i]=str1[i];
}
for (int i=0;i<MAXSIZE-strlen(str1)-1;i++) //这里所写的串都是从str[0]开始的,所以i<MAXSIZE-strlen(str1)-1
{
t[i+strlen(str1)]=str2[i];
}
cout<<"第二个字符串未完全连接!"<<endl;
}else
{
for (int i=0;i<strlen(str1);i++)
{
t[i]=str1[i];
}
cout<<"两个字符串连接失败!只显示第一个字符串内容!"<<endl;
}
return t;
}
//串的大小比较strcmp()
int strcmp(SString str1,SString str2)
{
int lenstr1=strlen(str1);
int lenstr2=strlen(str2);
int minstr=lenstr1>lenstr2? lenstr2:lenstr1;
int i=0;
while (i<minstr)
{
if (str1[i]==str2[i])
{
i++;
}else
{
return str1[i]-str2[i];
}
}
return lenstr1-lenstr2;
return 0;
}
//返回子串sub在串第pos个字符之后的位置函数Index()
int Index(SString str,SString sub,int pos)
{
int i=pos,j=1;
while (i<=strlen(str)&&j<=strlen(sub))
{
if (str[i]==sub[j])
{
i++;
j++;
}else
{
i=i-j+2
; //若串sub和串str中的子串只有前部分相同,则将i指向起始位置的后一位i-(j-1)+1
j=1;
}
}
if (j>strlen(sub)) //当循环结束时,j比sub长度大1
{
return i-strlen(sub); //当串str中有符合条件的子串,那么循环结束时i指向的是串str中与子串sub最后一个字符相等的字符的后一位
}else
{
return 0;
}
}
void main()
{
SString str1="12345qwerdfa";
cout<<"串str1为:"<<str1<<endl;
cout<<"串的长度为:"<<strlen(str1)<<endl<<endl;
SString str2="0";
strcpy(str2,str1);
cout<<"将串str1复制给str2,得到的str2为:"<<str2<<endl<<endl;
SString str3="0";
cout<<"从第3个位置开始截取串str1长度为5的子串str3,str3的值为:";
cout<<Substr(str3,str1,3,5)<<endl<<endl;
SString str4="12345678910"; //字符串数组最后一位是'/0'
SString str5="absadfsdfs4564dafl";
cout<<"串str4为:"<<str4<<endl;
cout<<"串str5为:"<<str5<<endl;
SString str6="0";
strcat(str6,str4,str5);
cout<<"将str4和str5连接后,得到的str6为:";
cout<<str6<<endl<<endl;
SString str7="12.47897";
SString str8="12/4798";
cout<<"串str7为:"<<str7<<endl;
cout<<"串str8为:"<<str8<<endl;
if (strcmp(str7,str8)==0)
{
cout<<"str7和str8相等."<<endl;
}else if (strcmp(str7,str8)>0)
{
cout<<"str7大于str8."<<endl;
}else
{
cout<<"str7小于str8."<<endl;
}
cout<<endl;
SString str9="12345678";
SString str10="567";
cout<<"串str9为:"<<str9<<endl;
cout<<"子串str10为:"<<str10<<endl;
cout<<"从第3个位置开始,在str9中子串为str10的开始位置是:"<<Index(str9,str10,4)<<endl<<endl;
}