将一个字符串str的内容颠倒过来,并输出。
数据范围:
import java.util.Scanner;
import java.util.Stack;
//有意思
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.nextLine();
Stack sta = new Stack();
for(char ch:str.toCharArray()){
sta.push(ch);
}
while(!sta.empty()){
System.out.print(sta.pop());
}
}
}
}
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String str = sc.nextLine();//next()是遇到空格;nextLine()是遇到回车 StringBuilder sb = new StringBuilder(str); System.out.println(sb.reverse().toString()); }}}
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string str; while (getline(cin,str)) { reverse(str.begin(), str.end()); cout << str << endl; } return 0; }
用栈先进后出的特性做:
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String s = sc.nextLine(); fun(s); } } public static void fun(String s){ Stack<Character> stack = new Stack<>(); int n = s.length(); for(int i=0; i<n; i++) stack.push(s.charAt(i)); while(n>0){ System.out.print(stack.pop()); n--; } } }
#include<stdio.h> #include<string.h> void reverse(char *ch) { char* left = ch; char* right = ch + strlen(ch) - 1; //左右值交换 while (left < right) { char temp = *right; *right = *left; *left = temp; left++; right--; } int i = 0; while (i < strlen(ch)) { printf("%c", ch[i]); i++; } } int main() { char ch[10000] = { 0 }; while (gets(ch)) { reverse(ch); } return 0; }
#这么写麻烦了,直接print(input()[::-1])就行 while True: try: s = input() s_reverse = s[::-1] print(s_reverse) except: break
#include<stdio.h> #include<string.h> int main(){ char str[10001]={'\0'}; while(gets(str)){ //注:这里不能使用scanf("%d",str)函数,含空格字符串会被视为多组输入。 int len=strlen(str); for(int i=len-1;i>=0;i--){ printf("%c",str[i]); }printf("\n"); } }
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { // 注意 while 处理多个 case StringBuilder b = new StringBuilder(in.nextLine()); System.out.println(b.reverse()); } } }
print(input()[::-1])正经点,倒序输出一下
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] str = br.readLine().trim().toCharArray(); for(int i = str.length - 1; i >= 0; i--) System.out.print(str[i]); System.out.println(); } }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { StringBuffer sb = new StringBuffer(sc.nextLine()); System.out.println(sb.reverse().toString()); } } }