字符串逆转
题意:输入一个字符串,逆向输出该串。
Sample Input
3
Frankly, I don't think we'll make much
money out of this scheme.
madam I'm adam
Sample Output
hcum ekam ll'ew kniht t'nod I ,ylknarF
.emehcs siht fo tuo yenom
mada m'I madam
方法一采用求解字符串长度,代码如下:
#include <iostream> #include <string.h> #include <stdio.h> #include <string> using namespace std; int main() { int n ; cin >> n ; getchar() ; while(n--) { char s[100] ; gets(s) ; int len = strlen(s) ; for(int i = len - 1 ; i >= 0 ; i--) cout << s[i] ; cout << endl ; } return 0; }
方法二采用字符数组赋值给字符串,调用reverse函数完成:
#include <iostream> #include <algorithm> using namespace std; int main () { int n; char ss[71]; string s; cin>>n; cin.get(); //吸收一个'\n',不然会影响到cin.getline() while (n--) { cin.getline(ss,71); s = ss; //讲字符数组赋值给字符串,太方便了 reverse(s.begin(),s.end()); cout<<s<<endl; } return 0; }
方法三采用JAVA完成:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in) ; int n = sc.nextInt() ; String get = sc.nextLine() ; //吸收换行符 while(n-- > 0) { String s = sc.nextLine() ; StringBuffer str = new StringBuffer(s) ; System.out.println(str.reverse()); } } }