題目描述
寫一函數,使輸入的一個字符串按反序存放,在主函數中輸入輸出反序後的字符串(不包含空格)。
輸入
一行字符
輸出
逆序後的字符串
樣例輸入
123456abcdef
樣例輸出
fedcba654321
第一種方法
#include<iostream>
#include<string>
using namespace std;
int main(){
string a;
cin>>a;
for(int i=a.length()-1;i>=0;i--){
cout<<a[i];
}
return 0;
}
第二種方法:https://blog.dotcpp.com/a/56771
解題思路:
字符串用string類型 頭文件#include <string>
在C++算法頭文件algorithm中包含了倒序的函數reverse。
#include <iostream> //標準輸入輸出流
#include <string> //字符串類型
#include <algorithm> //算法頭文件
int main()
{
std::string str; //定義字符串
std::cin>>str; //輸入字符串
reverse(str.begin(),str.end()); //逆序
std::cout<<str; //輸出逆序後的字符串
}
#include <iostream> //標準輸入輸出流
#include <string> //字符串類型
#include <algorithm> //算法頭文件
using namespace std;
int main()
{
string str; //定義字符串
cin>>str; //輸入字符串
reverse(str.begin(),str.end()); //逆序
cout<<str; //輸出逆序後的字符串
}
第三種方法
解題思路:此題的關鍵是在輸入字符串後,計算輸入的字符串的長度,這裏用到strlen()函數,然後在循環輸出倒序字符串
注意事項:strlen()函數要用到#include<string.h>頭文件
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char a[100];
cin>>a;
for(int i=strlen(a)-1;i>=0;i--)
cout<<a[i];
return 0;
}