How can I turn the entire text content into c#

Asked

Viewed 121 times

0

How can I get a file .txt and turn it into a chain of integers?

My program has to take the matrix that is inside the file .txt and put inside a matrix in the program so I can manipulate the data inside the matrix. The part that opens the file I’ve done, but I’m not finding a way to transform the matrix within the .txt in a matrix within my program. Please someone help me.

The .txt contain this data:

0 1 0 0 0 0 0

1 0 1 0 0 0 0

0 1 0 1 1 1 0

0 0 1 0 1 1 0

0 0 1 1 1 1 0

0 0 1 1 1 0 0

0 0 0 0 0 1 1
  • 2

    What is the data format in the file ? Put an example of this file txt and the code you already have to read.

  • Without an example of how ta the text becomes difficult...

1 answer

3


You can split each line of the file with the split by ' n' and then split each line and go putting in your matrix, for example:

        var matriz = new int[10, 10];
        var texto = File.ReadAllText("Caminho para o arquivo");

        int i = 0, j = 0;
        foreach (var linha in texto.Split('\n'))
        {
            foreach (var letra in linha.Split(' '))
            {
                //verifica se o caracter não é nulo ou vazio
                if (string.IsNullOrWhiteSpace(letra))
                    continue;

                matriz[i, j] = Convert.ToInt32(letra);
                j++;
            }
            i++;
            j = 0;
        }
  • Leandro, could you explain to me why the n please

  • 1

    The ' n' character is responsible for breaking the lines of the text, that is, when you are typing a text and pressing a "enter" you actually added the ' n' character to your text, the text readers when identifying the ' n' know that they must break a line. When splitting the text in ' n', you created an array that contains all the lines of your text. Did you understand? https://pt.wikipedia.org/wiki/Nova_line

Browser other questions tagged

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