MyStrlen, MyStrcmp, MyReverse,MyStrcpy,MyStrncpy,Merge,Change
#include <iostream>
#include <cstring>
#include <cassert>
using namespace std;
int MyStrlen(char* a) //strlen(a)
{
int i=0;
while(a[i]!='\0')
{
i++;
}
return i;
}
int MyStrcmp(char* s, char* t)
{
assert(s!=NULL);
assert(t!=NULL);
while(*s && *t && (*s==*t))
{
s++;
t++;
}
if(*s>*t)
{
return 1;
}
else if(*s<*t)
{
return -1;
}
else
{
return 0;
}
}
void MyReverse(char* a) //头尾交换
{
int size= MyStrlen(a); // strlen(a);
for(int i=0; i<size/2; i++)
{
char temp=a[i];
a[i]=a[size-1-i];
a[size-1-i]=temp;
}
}
char* MyStrcpy(char* dest, char* src)
{
assert(dest!=NULL);
assert(src!=NULL);
int i=0;
for(; src[i]!='\0'; i++)
{
dest[i]=src[i];
}
dest[i]='\000';
return dest;
}
char* MyStrncpy(char*dest, char* src, int pos)
{
assert(dest!=NULL);
assert(src!=NULL);
int SizeSrc=MyStrlen(src);
if(SizeSrc>=pos)
{
int i=0;
for(; i<pos; i++)
{
dest[i] =src[i];
}
return dest;
}
else
{
int i=0;
for(;i<SizeSrc; i++)
{
dest[i]=src[i];
}
//dest[i]='\0';
return dest;
}
}
char* Merge(char* dest, char* src)//strcat
{
int i=0;
int j=0;
while(dest[i] !='\0')
{
i++;
}
while(src[j] !='\0')
{
dest[i] = src[j];
i++;
j++;
}
dest[i]='\0';
return dest;
}
char* Change(char* a, int pos) // 指定位置前后对换位 pos=3 abc defg -> defg abc
{
char* temp=new char[pos+1];
MyStrncpy(temp, a, pos);
temp[pos]='\0';
MyStrncpy(a,a+pos,7-pos);
MyStrncpy(a+7-pos,temp,pos);
delete [] temp;
return a;
}
int main()
{
char a[]="abcdefg";
cout<<"size of the char a[]: ";
cout<<MyStrlen(a)<<endl;
cout<<"Initial char a[]: ";
cout<<a<<endl;
MyReverse(a);
cout<<"after reverse char a[]: ";
cout<<a<<endl;
cout<<"after shabi dadong: ";
cout<<Change(a,4)<<endl;
return 0;
}
关注公众号 海量干货等你