3 回答
TA贡献1851条经验 获得超3个赞
请参阅我更改的行上的评论:
向后迭代字符串
不要在每次循环迭代中打印每个双字符,因为您正在连接最终结果
循环后打印最终结果
import java.util.Scanner;
public class ReverseDoubleChar {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string ");
String str = input.nextLine();
String new_str = "";
String result = "";
for (int i = str.length() - 1; i >= 0; i--) { //Iterate through string backwards
result += str.substring(i, i + 1) + str.substring(i, i + 1); //Concatenation
String result2 = null;
result2 = result;
// System.out.println(result2); //Don't print each double char since you're concatenating above
}
System.out.println(result); //Print full double-charred string after loop
}
}
输出:
Enter a string
string
ggnniirrttss
TA贡献1818条经验 获得超7个赞
使 for 循环向后迭代:
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
String s = str.substring(i, i + 1);
result += s + s;
}
System.out.println(result);
或使用转发循环:
String result = "";
for (int i = 0; i < str.length(); i++) {
String s = str.substring(i, i + 1);
result = s + s + result;
}
System.out.println(result);
TA贡献1856条经验 获得超5个赞
也许使用 StringBuilder 而不是做你自己的子字符串和连接。
public class ReverseDoubleChar {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string ");
StringBuilder str = new StringBuilder(input.nextLine());
StringBuilder result = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
result.append(str.charAt(i));
result.append(str.charAt(i));
}
System.out.println(result.toString());
}
}
添加回答
举报