C++编程 编写字符串反转函数mystrrev

2025-04-24 19:20:25
推荐回答(3个)
回答1:

应用C++的string类对象实现。为体现一般性,对象中就允许空格出现;自定义逆序函数形参应使用引用类型,以便永久性改变对实参对象的操作。举例代码如下:

//#include "stdafx.h"//If the vc++6.0, with this line.
#include 
#include 
using namespace std;
void mystrrev(string &str){//引用形参,以改变实参
for(int j=str.length()-1,i=0;i char t=str[i];
str[i]=str[j],str[j]=t;
}
}
int main(int argc,char *argv[]){
string s;
char ch;
cout << "Input a string...\ns=";
while((ch=cin.get())!='\n')//输入可有空格
s+=ch;
cout << "The original string: " << s << endl;//逆序前
mystrrev(s);//调用自定义逆序函数
cout << "After reverse order: " << s << endl;//逆序后
return 0;
}

运行结果举例:

回答2:

/*
    Author:QCQ
    Date:2015-4-11
    e-mail:qinchuanqing918@163.com
 */
#include
#include
#include
#include
using namespace std;
void mystrrev(char str[]);
int main()
{
    char temp[30];
    while(gets(temp)){
        cout<        mystrrev(temp);
        cout<    }
    return 0;
}

void mystrrev(char str[]){
    char *pbegin = str;
    char *pend = str + strlen(str) - 1;
    while(pbegin < pend)
    {
        char tmp;
        tmp=*pbegin;
        *pbegin=*pend;
        *pend=tmp;
        ++pbegin;
        --pend;
    }
}

回答3: