例如,我想将每个字符串向后打印两次(字符串-> ggnniirrttss)
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 = 0; i < str.length(); i++) {
result += str.substring(i, i + 1) + str.substring(i, i + 1);
String result2 = null;
result2 = result;
System.out.println(result2);
}
}
}
但是,当我输入此代码时,我得到的只是
ss
tt
rr
ii
nn
gg
全部换行。有人知道如何解决这个问题吗?谢谢
答案 0 :(得分:0)
使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);
答案 1 :(得分:0)
在我更改的行上查看评论:
在循环后打印最终结果
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
答案 2 :(得分:0)
也许使用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());
}
}
答案 3 :(得分:0)
String result="";
for(int i=0;i<str.length();i++){
result=result+str.charAt(i)+ str.charAt(i);
}
return result;
此代码可以正常工作。