串的基本操作实现
为什么s3在拼接之前能够输出但是拼接之后不能输出
必须要放在数组里吗
#include <iostream>
using namespace std;
int strlen(char *s)
{
char *p=s;
int len=0;
while(*p!='\0')
{
p++;
len++;
}
return len;
}
char *stract(char *s1,char *s2)
{
char *p=s1,*q=s2;
while(*p!='\0')
{
p++;
}
while(*q!='\0')
{
*p=*q;
p++;q++;
}
*p='\0';
return s1;
}
int strcmp(char *s1,char *s2)
{
char *p=s1,*q=s2;
while(*p!='\0'&&*q!='\0')
{
if(*p>*q)
return 1;
else if(*p<*q)
return -1;
else
{p++;q++;}
}
if(*p!='\0'&&*q!='\0')
return 0;
if(*p!='\0')
return 1;
if(*q!='\0')
return -1;
}
int main()
{
char s1[20]="I love ",*s2="China!";
cout<<"The length of s1:"<<endl;
cout<<strlen(s1)<<endl;
cout<<"The length of s2:"<<endl;
cout<<strlen(s2)<<endl;
cout<<"s1>s2?"<<endl;
cout<<strcmp(s1,s2)<<endl;
cout<<"s2>s1?"<<endl;
cout<<strcmp(s2,s1)<<endl;
cout<<"s1+s2:"<<endl;
stract(s1,s2);
for(int i=0;s1[i]!='\0';i++)
{
cout<<s1[i];
}
cout<<endl;
char *s3="hello ",*s4="world";
cout<<s3<<endl;
stract(s3,s4);
cout<<s3<<endl;
return 0;
}