一些常见的字符串处理函数实现
字符串拷贝
char* strcpy(char* strDest,const char* strSrc) { assert(strDest!=NULL && strSrc!=NULL); char* strTmp = strDest; while(*strSrc!='\0') { *strDest++ = *strSrc++; } strDest = '\0'; return strTmp; }
内存拷贝
void * memcpy(void* strDest,void* strSrc,size_t size) { assert(strDest!=NULL && strSrc != NULL); void* strTmp = strDest; //考虑内存重叠情况 类似memmove if (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; } } return strTmp; }
求字符串大小
int strlen(const char*strSrc) { assert(strSrc!= NULL); int len = 0; while((*strSrc++) != '\0') ++len; return len; }
两字符串连接
char* strcat(char* strDest,const char* strSrc) { assert((strDest != NULL) && (strSrc != NULL)); char* strTmp = strDest; while(*strDest != '\0') ++strDest; while(*strDest++ = *strSrc++) ; *strDest++ = '\0'; return strDest; }
字符串转×××数处理
int myAtoi(char* strSrc) { int iValue = 0; int flag=0; while (*strSrc == ' ') { strSrc++; } if(*strSrc == '-') { flag = -1; } else if(*strSrc == '+') { flag = 1; } else if(*strSrc > '9' || *strSrc < '0') { return 0; } while(*strSrc>='0' && *strSrc <= '9' && *strSrc ) { iValue = iValue*10 + *strSrc -'\0'; strSrc++; } if(flag == 0) iValue = iValue*(-1); return iValue; }
判断输入的是否是回文
bool isPalindrome(char* input) { if(input == NULL) return false; char* strBegin = input; char* strEnd = input+strlen(input)-1; while (strBegin < strEnd) { if(*strBegin++ != *strEnd--) return false; } return true; }
把一个char组成的字符串循环右移n个 void loopMove(char* pStr,int steps) { int nLen = strlen(pStr); if(nLen <= 0 || steps == 0) return; int nStep = steps % nLen; if(nStep == 0) return; char strTmp[128]; memcpy(strTmp,pStr+nLen-nStep,nStep); memcpy(strTmp+nStep,pStr,nLen-nStep); memcpy(pStr,strTmp,nLen); }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。