字符串常見編程題

#include
#include <iostream>
using namespace std;


bool isOK=false;


int StringToInt(const char *s){
bool neg=false;
const char *p=s;
int num=0;
if (s[0]==NULL)
{
return 0;
}
if (s[0]=='-')
{
neg=true;
p++;


}
else if(s[0]=='+')
p++;
while(*p!='\0'){
if(*p>='0'&&*p<='9'){
num=num*10+(*p-'0');
p++;
}
else
{
cout<<"存在非法輸入"<<endl;
break;
}
}
if (*p=='\0')
{
isOK=true;
if (neg==true)
{
num=-num;
}
}


return num;
}
//整個字符串逆序
char* RevStr(char* s){
if (s==NULL)
{
      return s;
}
char *front=s;
char *end=s;
while(*end!='\0')
end++;
end--;
while(front<end){
char temp=*front;
        *front =*end;
*end= temp;
front++;
end--;
}
return s;


}
void RevStr(char *s,int length){
if (s==NULL)
{
return ;
}
char *front=s; 
char *end=front+length-1;
while(front<end){
char temp=*front;
*front =*end;
*end= temp;
front++;
end--;
}
}
//按單詞逆序
char* ReveachWord(char *s){
if(s==NULL){
return s;
}
char *pbegin=s;
char *pend=s;
while(*pbegin!='\0'){
while((*pend!=' ')&&((*pend)!='\0')){
pend++;
}
RevStr(pbegin,(pend-pbegin));
if (*pend=='\0')
{
break;
}
else{
pbegin=++pend;
pend=pbegin;
}
}
RevStr(s,strlen(s));
return s;
}
//比較兩個字符串
int comparestring(char *s1,char *s2){
while (*s1!='\0'&&*s2!='\0'&&*s1==*s2){
s1++;
s2++;
}
if (*s1=='0'&&*s2=='\0')
{
return 0;
}
if(*s1=='\0')
return -1;
else  return 1;
return(*s1-*s2);


}
char* Strcpy(char* strDest,char *strSrc){
if (strSrc==NULL||strDest==NULL)
{
return NULL;
}
char* strDestCopy=strDest;//少了這句,保存首地址
while((*strDest++=*strSrc++)!='\0');
return strDestCopy;
}
//strstr
const char* Strstr(const char* str1,const char* str2){
if(str1==NULL||str2==NULL)
return NULL;
const char *p1=str1;
const char *p2=str2;
do 
{

while(*p1!=*str2)
{
p1++;
}
const char *temp1=p1;
const char *temp2=p2;
while(*p1==*p2)
{p1++;
p2++;}//這裏出現錯誤,相等以後才能加,不能寫成*p1++=*p2++
if (*p2=='\0')
{
return temp1;
}
else 
{p2=str2;
p1=temp1++;}
} while (p2!='\0'&&p1!='\0');
return NULL;
}
//未完待寫
char* maxsubstr(char *s1,char *s2){
if(s1==NULL||s2==NULL)
return NULL;
char *begin1=s1;
char *begin2=s2;
int maxnum=0;
char *maxsub=NULL;

while(*s1!='\0'){
while(*begin1!=)



}

}
int main()
{
//輸入一個字符串,將其按整數輸出
/*char *s="-1234";
int schange=StringToInt(s);
cout<<schange<<endl;
char s2[]="hello";
cout<<RevStr(s2)<<endl;
char s3[]="This is a sentence";
cout<<ReveachWord(s3)<<endl;
cout<<comparestring(s2,s3);
char s4[20];
cout<<Strcpy(s4,s3)<<endl;*/
char s5[]="abcdefg";
char s6[]="de";
cout<<Strstr(s5,s6)<<endl;
return 0;
//複製字符串



}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章