作业帮:字符串反转(头部插入)
题目描述:
不借助内置函数实现字符串反转
输入
I am a student.
输出
.tneduts a ma I
代码:
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int length = str.length(); String reverse = ""; for (int i = 0; i < length; i++) { reverse = str.charAt(i) + reverse; } System.out.println(reverse); } }
还有很多
方法一:(利用递归实现) public static String reverse1(String s) { int length = s.length(); if (length <= 1) return s; String left = s.substring(0, length / 2); String right = s.substring(length / 2, length); return reverse1(right) + reverse1(left); //调用递归 } 方法二:(拼接字符串) public static String reverse2(String s) { int length = s.length(); String reverse = ""; for (int i = 0; i < length; i++) reverse = s.charAt(i) + reverse; return reverse; } 方法三:(利用数组,倒序输出) public static String reverse3(String s) { char[] array = s.toCharArray(); String reverse = ""; for (int i = array.length - 1; i >= 0; i--) reverse += array[i]; return reverse; } 方法四:(利用StringBuffer的内置reverse方法) public static String reverse4(String s) { return new StringBuffer(s).reverse().toString(); } 方法五:(利用临时变量,交换两头数值) public static String reverse5(String orig) { char[] s = orig.toCharArray(); int n = s.length - 1; int halfLength = n / 2; for (int i = 0; i <= halfLength; i++) { char temp = s[i]; s[i] = s[n - i]; s[n - i] = temp; } return new String(s); } 方法六:(利用位异或操作,交换两头数据) public static String reverse6(String s) { char[] str = s.toCharArray(); int begin = 0; int end = s.length() - 1; while (begin < end) { str[begin] = (char) (str[begin] ^ str[end]); str[end] = (char) (str[begin] ^ str[end]); str[begin] = (char) (str[end] ^ str[begin]); begin++; end--; } return new String(str); } 方法七:(利用栈结构) public static String reverse7(String s) { char[] str = s.toCharArray(); Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < str.length; i++) stack.push(str[i]); String reversed = ""; for (int i = 0; i < str.length; i++) reversed += stack.pop(); return reversed; }