0

I need to implement the Array.Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) in a function.

The array it gets is a char[] array here is my implementation but it doesn't work:

private char[] ArrayCopier(char[] chars, int startIndex, int length)
        {
            char[] NewArray = new char[length];
            int index = 0;

            for (int i = startIndex; i < length; i++)
            {
                NewArray[index] = chars[i];
            }

            return NewArray;
        }
3
  • 1
    You forgot to increment index counter. Commented Dec 6, 2020 at 12:10
  • @DavidPivovar Ahh thanks, but still doesn't work :( Commented Dec 6, 2020 at 12:13
  • And i < (length + startIndex). Commented Dec 6, 2020 at 12:21

2 Answers 2

1

Inside your for loop you need index++; otherwise it will put every char in the first position of your new array.

Also I'd check that you don't go beyond the bounds of your source array.

So:

private char[] ArrayCopier(char[] chars, int startIndex, int length)
        {
            char[] NewArray = new char[length];
            int index = 0;

            for (int i = startIndex; (i < length)&&(i<chars.length); i++)
            {
                NewArray[index] = chars[i];
                index++;

            }

            return NewArray;
        }

Sign up to request clarification or add additional context in comments.

Comments

0

This should solve your problem:

private char[] ArrayCopier(char[] chars, int startIndex, int length)
{
    // make sure startIndex is within the bounds of the given array
    if (startIndex < 0 || startIndex >= chars.Length)
        throw new IndexOutOfRangeException();

    // if necessary, recalculate length to be within the array boundaries
    if (startIndex + length > chars.Length)
        length = chars.Length - startIndex;

    var result = new char[length];

    for (int i = 0; i < length; i++)
        result[i] = chars[i + startIndex];

    return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.