For string processing problems, we often encounter problems that directly or indirectly need to flip (reverse) strings in the written test. Here are some methods (but not limited to):
Method 1: Use the toCharArray( ) method, then reverse the assignment
import java.util. *; public class Test5{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ char[] c1 = sc.next().toCharArray(); int len = c1.length; char[] c2 = new char[len]; for(int i = 0; i < len; i ++){ c2[i] = c1[len-1-i]; } String res = new String(c2); System.out.println(res); } } }
Method 2: Use the reverse( ) method of the StringBuilder class
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ System.out.println(new StringBuilder(sc.next()).reverse()); } } }
Method 3: If only consider the output, do not consider the return
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String s = sc.next(); for(int i = s.length()-1; i >= 0; i--) System.out.print(s.charAt(i)); } } }
Method 4: Use the static method reverse( ) of collections
import java.util. *; public class Test5{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ /* char[] c = sc.next().toCharArray(); List<Character> list = new ArrayList<Character>(); for(int i =0;i<c.length;i++) list.add(c[i]); Collections.reverse(list); for(Character cha:list) System.out.print(cha); */ String[] s = sc.nextLine().split(""); List<String> list = Arrays.asList(s); Collections.reverse(list); for(String s1:list) System.out.print(s1); } } }