How to create an array the same size as another array without copying it?

Asked

Viewed 43 times

0

    private void InversaoString(string Texto, int Tamanho)
    {
        char[] arrChar = Texto.ToCharArray();
        char arrChar2;
        int indice = 0;
        for(Tamanho = arrChar.Length-1; Tamanho>=0; Tamanho--)
        {
            arrChar2(indice) = arrChar;
            indice++;
        }
        string Novo = new string(arrChar2);
        txtSaida.Text = Novo;

    }

See that there I copy the string Texto for an array. Just below I create another array, only that it has one however, I want to arrChar2 be the same size as arrChar, I tried using the method Length but without success. How should I proceed? (I want to do this because I want to invert the string Text).

1 answer

0


With Length works normally, looks an example:

private string InversaoString(string Texto)
{
    char[] arrChar = Texto.ToCharArray();
    char[] arrChar2 = new char[arrChar.Length];

    for (int i = arrChar.Length - 1, i1 = 0; i >= 0; i--, i1++)
        arrChar2[i1] = arrChar[i];

    return new string(arrChar2);
}

To call the function do so:

Console.WriteLine(InversaoString("Teste"));
  • Thanks Roberto, it worked here. The exercise is to make recursive, now I have idea of how to make it recursive, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.