用每个字符两次打印一个字符串

时间:2020-06-24 03:36:56

标签: java arrays for-loop

package com.pack7;
/* The task is to take a string and print the string again but this time every 
 *character print twice. say input is:"java", output should be :"jjaavvaa" 
 */
public class ClassB {
    
    public String doubleChar(String str)
    {
        char[] ch = str.toCharArray();//converted the given string to char array
        char[] ch2 = new char[ch.length*2];//created another array of twice the length of first array
        for(int i=0;i<ch.length;i++)
        {
            ch2[i]=ch[i];//assigning 1st char of 1st array in the 2nd array(index 0)
            ch2[i+1]=ch[i];//assigning 1st char of 1st array in the 2nd array(index 0+1)
        }
        
        String result = new String(ch2);//and passing the 2nd array as parameter to create string
        return result;// returning the string as answer
        
    }
    
    public static void main(String[] args) 
    {
        ClassB obj = new ClassB();
        String s = obj.doubleChar("java");
        System.out.println(s);//but it prints "javaa", i can't figure out why my logic is not working
    }

}

1 个答案:

答案 0 :(得分:1)

这是一个愚蠢的程序。您的循环覆盖了之前的迭代 字符,因为您没有正确计算ch2索引。试试这个:

for(int i=0;i<ch.length;i++)
{
    ch2[2*i]=ch[i];//assigning 1st char of 1st array in the 2nd array(index 0)
    ch2[2*i+1]=ch[i];//assigning 1st char of 1st array in the 2nd array(index 0+1)
}