常见的字符串处理函数实现
一些常见的字符串处理函数实现
字符串拷贝
char*strcpy(char*strDest,constchar*strSrc){assert(strDest!=NULL&&strSrc!=NULL);char*strTmp=strDest;while(*strSrc!='\0'){*strDest++=*strSrc++;}strDest='\0';returnstrTmp;}
内存拷贝
void*memcpy(void*strDest,void*strSrc,size_tsize){assert(strDest!=NULL&&strSrc!=NULL);void*strTmp=strDest;//考虑内存重叠情况类似memmoveif(strDest<=strSrc||(char*)strDest>=(char*)strSrc+size){while(size--){*(char*)strDest=*(char*)strSrc;strDest=(char*)strDest+1;strSrc=(char*)strSrc+1;}}else{strDest=(char*)strDest+size-1;strSrc=(char*)strSrc+size-1;while(size--){*(char*)strDest=*(char*)strSrc;strDest=(char*)strDest-1;strSrc=(char*)strSrc-1;}}returnstrTmp;}
求字符串大小
intstrlen(constchar*strSrc){assert(strSrc!=NULL);intlen=0;while((*strSrc++)!='\0')++len;returnlen;}
两字符串连接
char*strcat(char*strDest,constchar*strSrc){assert((strDest!=NULL)&&(strSrc!=NULL));char*strTmp=strDest;while(*strDest!='\0')++strDest;while(*strDest++=*strSrc++);*strDest++='\0';returnstrDest;}
字符串转×××数处理
intmyAtoi(char*strSrc){intiValue=0;intflag=0;while(*strSrc==''){strSrc++;}if(*strSrc=='-'){flag=-1;}elseif(*strSrc=='+'){flag=1;}elseif(*strSrc>'9'||*strSrc<'0'){return0;}while(*strSrc>='0'&&*strSrc<='9'&&*strSrc){iValue=iValue*10+*strSrc-'\0';strSrc++;}if(flag==0)iValue=iValue*(-1);returniValue;}
判断输入的是否是回文
boolisPalindrome(char*input){if(input==NULL)returnfalse;char*strBegin=input;char*strEnd=input+strlen(input)-1;while(strBegin<strEnd){if(*strBegin++!=*strEnd--)returnfalse;}returntrue;}
把一个char组成的字符串循环右移n个voidloopMove(char*pStr,intsteps){intnLen=strlen(pStr);if(nLen<=0||steps==0)return;intnStep=steps%nLen;if(nStep==0)return;charstrTmp[128];memcpy(strTmp,pStr+nLen-nStep,nStep);memcpy(strTmp+nStep,pStr,nLen-nStep);memcpy(pStr,strTmp,nLen);}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。