将字符串进行反转
方法一:
//定义String
String text = "abcdefr";
//反转后的String
String newText = "";
//循环取出每一个字符
for (int i = 0; i < text.length(); i++) {
//倒序拼接
newText = text.charAt(i)+newText;
}
System.out.println(newText);
这种方法来说是有点效率上的问题上的,具体分析请查看
String 的详细分析
方法二
//定义String
String text = "abcdefr";
//创建 StringBuilder
StringBuilder stringBuilder = new StringBuilder();
//循环遍历取出
for (int i = text.length()-1; i >=0; i--) {
//倒序取出 拼接
stringBuilder.append(text.charAt(i));
}
//转成新的 String
String string = stringBuilder.toString();
System.out.println(string);
方法三
//定义String
String text = "abcdefr";
StringBuilder stringBuilder = new StringBuilder(text);
//反转
stringBuilder.reverse();
//反转后的 String
String newString = stringBuilder.toString();
System.out.println(newString);
方法四
//定义String
String text = "abcdefr";
//将String 转字符数组
char[] textChars = text.toCharArray();
int n = textChars.length - 1;
int halfLength = n / 2;
//循环将 字符数组中的字符反转
for (int i = 0; i <= halfLength; i++) {
//反转替换
char temp = textChars[i];
textChars[i] = textChars[n - i];
textChars[n - i] = temp;
}
//构造反转后的 String
String newString = new String(textChars);
System.out.println(newString);
方法五
//定义String
String text = "abcdefr";
//转字符数组
char[] str = text.toCharArray();
//创建 Stack
Stack<Character> stack = new Stack<Character>();
//将字符保存到Stack中
for (int i = 0; i < str.length; i++){
stack.push(str[i]);
}
//定义 SingBuilder
StringBuilder stringBuilder = new StringBuilder();
//将Stack中的字符取出 添加到StringBuilder中
for (int i = 0; i < str.length; i++){
stringBuilder.append(stack.pop());
}
//反转后的 String
String rverseString = stringBuilder.toString();
System.out.println(rverseString);