Java 字符串中字符的逐步复制

Java 字符串中字符的逐步复制,java,string,recursion,for-loop,Java,String,Recursion,For Loop,我是一名Java初学者,希望获得一些帮助,帮助我编写只使用main方法逐步复制给定字符串中每个字符的代码 那么比如说, 输入字符串:Hello(但是代码应该适用于任何字符串) 输出: 嗯 HHee 海勒 海厄尔 Hheelloo 因此,在复制每个字符并将其添加到以前的任何复制中之后,程序将终止。这需要多个循环吗 到目前为止,我有以下代码: for (int i = 0; i < length ; i++) { char c = s.charAt(i); System.out

我是一名Java初学者,希望获得一些帮助,帮助我编写只使用main方法逐步复制给定字符串中每个字符的代码

那么比如说,

输入字符串:Hello(但是代码应该适用于任何字符串)

输出:

嗯 HHee 海勒 海厄尔 Hheelloo

因此,在复制每个字符并将其添加到以前的任何复制中之后,程序将终止。这需要多个循环吗

到目前为止,我有以下代码:

for (int i = 0; i < length ; i++) {
    char c = s.charAt(i);
    System.out.println(c);

    int j = 0;
    while (j < length) {
    j = j+1;
    i++;
    s = new StringBuffer(s).insert(i, c).toString();

    System.out.println(s);
}

}
for(int i=0;i

我正在尝试嵌套循环,因为我认为这是解决问题的方法,但我没有接近。如果您能提供任何帮助或指导,我将不胜感激。…

-您正在重用变量I。确保在每个步骤上检查其值 -并检查substring()方法的使用情况

直接:

public static void main(String []args){
        String s="Hello"; //if you need to keep the original array, save it in temp and work with temp
        String prefix="";
        while(!s.equals("")){
            char c=s.charAt(0);
            prefix+=""+c+c;
            System.out.print(prefix+" ");
            s=s.substring(1);
        }
    }

看看你正在递增的变量和循环变量的
,那么我应该使用第二个int变量吗?我的代码现在是这样的:for(inti=0;ipublic static void main(String []args){
        String s="Hello"; //if you need to keep the original array, save it in temp and work with temp
        String prefix="";
        while(!s.equals("")){
            char c=s.charAt(0);
            prefix+=""+c+c;
            System.out.print(prefix+" ");
            s=s.substring(1);
        }
    }