PTA - 逆序字符串【C++引用】

逆序字符串(C++引用)

题目:设计一个void类型的函数reverse_string,其功能是将一个给定的字符串逆序。例如,给定字符串为“hello”,逆序后为“olleh”。

函数接口定义如下:

/* 函数原型参见main函数 */

裁判测试程序样例:

#include <iostream>
#include <string>
using namespace std;

/* 你的代码将嵌在这里 */

int main(int argc, char const *argv[])
{
    string str;
    getline(cin, str);		//输入字符串
    reverse_string(str); 	//逆序字符串str
    cout << str << endl;	//输出逆序后的字符串
    return 0;
}

输入样例:

hello

输出样例:

olleh

void reverse_string(string &s)   // 形参s是是实参str的别名 
{
    int N = s.size();            // 或 N = s.length(); 
    for (int i = 0; i < N / 2; i++)
    {
        char temp;
        temp = s[i];
        s[i] = s[N - i - 1]; 
        s[N - i - 1] = temp;
    }
} 

猜你喜欢

转载自blog.csdn.net/weixin_43821410/article/details/89532430