我需要让我的代码以相反的顺序输出字符串。例如,输出应将"代码"返回为"edoc"。这就是我到目前为止所做的。
public String reverseString(String str) {
String res = "";
for (int i = 0; i <= str.length()-1; i++) {
res = res + str.charAt(i);
}
return res;
}
你这样做的方式的主要问题是你从str中获取第n个字符并附加它,使其成为res的第n个字符。
你可以这样修复它:
public String reverseString(String str) {
String res = "";
for (int i = str.length() - 1; i >= 0; i--) {
res = res + str.charAt(i);
}
return res;
}
你的串联是向后的。尝试:
public String reverseString(String str) {
String res = "";
for (int i = 0; i < str.length(); i++) {
res = str.charAt(i) + res; // Add each char to the *front*
}
return res;
}
另请注意更简单的规范循环终止条件。
public class ReverseString {
//1. using for loop and charAt
public static void main(String[] args)
{
String s="Selenium";
String reverse="";
for(int i=s.length()-1;i>=0;i--)
{
reverse=reverse+(s.charAt(i));
}
System.out.println(reverse);
}