javastringcharoff-by-one

Off by one error for char-ing string


This method is supposed to take in a string and output the string as chars however it should be double the size. Example: the string is "PaRty" return should be 'P', 'P', 'a', 'a', 'R', 'R', 't', 't', 'Y', 'Y'

For my code, when I run the test it says that the arrays differed at element [];expected: but was:

I can not figure out was is wrong and was hoping someone can help point something out for me to understand and make this work please? And if I am off by one please explain?

//Implementing the second method: toExpandedArray, which works with 
//a string and then returns chars of that string. 
public static char[] toExpandedArray(String string)
{
    //Initializing variable needed to char the string
    char[] charArray = new char[string.length() * 2];     

    //The loop that will turn the string into characters.
    for (int i = 0; i < string.length(); i++)
    {            
     charArray[i] = string.charAt(i) ;
     charArray[i+1] = charArray[i];
     i++;
    }

    //Returning the characters as an array.
    return charArray;

Solution

  • Your copying logic is incorrect. You need to copy the letter from index i to index 2*i and 2*i + 1. The i++ at the end is unnecessary; it's already done in the for loop. Change

    charArray[i] = string.charAt(i);
    charArray[i+1] = charArray[i];
    i++;
    

    to

    charArray[2*i] = string.charAt(i);
    charArray[2*i+1] = string.charAt(i);