Tapan Das
Tapan Das

Reputation: 43

To print a string with every character twice

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
    }

}

Upvotes: 0

Views: 1151

Answers (1)

RufusVS
RufusVS

Reputation: 4127

It's kind of a silly program. Your loop was overwriting the previous iteration characters because you weren't calculating the ch2 index correctly. Try this:

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)
}

Upvotes: 1

Related Questions