Replace is not working C#

Asked

Viewed 386 times

1

I’m replacing one code with another in each row that the code is found on. But replace simply doesn’t work, goes through it and the line continues the same way. As you can see in the image below, if I use inside the immediate, it appears that it worked, but when checking the contents of the string I see that it continued the same way. inserir a descrição da imagem aqui

        string texto = string.Empty;
        int contadorCodigos = 0;
        int contadorLinhas = 0;
        string linha = string.Empty;
        string[] linhas = new string[_linhas.Count()];

        foreach (string line in _linhas)
        {
            linha = line;

            foreach (var item in _codigos)
            {
                if (line.Contains(item.Key))
                {
                    linha.Replace(item.Key, item.Value);
                    //line.Replace(item.Key, item.Value);
                    texto += $" {item.Key} - {item.Value};";
                    contadorCodigos++;
                    break;
                }
            }

            linhas[contadorLinhas] = linha;
            contadorLinhas++;
        }

        txtResultado.Text = texto;
        txtQtdCodigosTrocados.Text = contadorCodigos.ToString();

Does anyone know what might be going on?

1 answer

6


The method Replace() returns a value, and that value is that you are not accumulating anywhere.

Change your line to:

linha = linha.Replace(item.Key, item.Value);

So you will accumulate the result of Replace() back in variable linha as expected.

  • 1

    Thank you very much Thiago, stupid mistake on my part rsrs

  • 1

    Honest mistake. It happens to everyone.

Browser other questions tagged

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