字符串部分操作的函数实现
来源:互联网 发布:淘宝新开网店怎么推广 编辑:程序博客网 时间:2024/06/14 02:22
#include <iostream>using namespace std;/*求sub字符串在src中匹配的位置,匹配失败返回-1*/int findStr(const char*src,const char*sub){if(src==NULL || sub==NULL)return -1;const char * srcp;const char * subp;int index=-1;while(*src!=0){index++;srcp=src++;subp=sub;while(*srcp++==*subp++){if(*subp==0)return index;}}return -1;}/*字符串翻转*/void revStr(char* str){if(str==NULL)return;int length=strlen(str);int midIndex=(length%2==0)?(length/2):(length/2+1);for(int i=0;i<midIndex;++i){char temp=str[i];str[i]=str[length-i-1];str[length-i-1]=temp;}}/*判断是否是回文*/bool isHuiWen(const char *str){int length=strlen(str);int midIndex=length/2;bool huiWen=true;for(int i=0;i<midIndex;i++){if(str[i]!=str[length-i-1]){huiWen=false;break;}}return huiWen;}/*字符串的比较,前者大返回1,后者大返回-1,相等返回0*/int myStrCmp(const char* src,const char * dst){int ret=0;while( !(ret=*src-*dst) && *dst){src++;dst++;}if(ret>0)ret=1;else if(ret<0)ret=-1;return ret;}/*获取字符串长度,这种方法在求长字符串时较快速*/int getStrLen(const char *str){const char *temp=str;while(*str++!=0);return str-temp-1;}int main(){cout<<findStr("chen","he")<<endl;char str1[]="hello";revStr(str1);cout<<str1<<endl;cout<<isHuiWen("hello")<<endl;cout<<isHuiWen("chehc")<<endl;cout<<myStrCmp("chen","chen")<<endl;cout<<myStrCmp("che","chen")<<endl;cout<<myStrCmp("chen","che")<<endl;cout<<getStrLen("chen")<<endl;return 0;}