Adds number on each line in C #

3

How to remove the numbering of this line and then add it again in another format?

Input:
N0006 G90
N0007 G90
N0008 G92 X21.7301 Y88.9657
N0009 S555
N0010 D14
N0011 G42 G01 X22.0659 Y89.3015 
N0012 X22.4194 Y89.655 
N0013 (PATHSTART0)

Output:

N1 G90
N2 G90
N3 G92 X21.7301 Y88.9657
N4 S555
N5 D14
N6 G42 G01 X22.0659 Y89.3015 
N7 X22.4194 Y89.655 
N8 (PATHSTART0)

I would have to go through the text file right? But how can I identify the numbering of the beginning? Are these codes sometimes up to 10 thousand lines?

    
asked by anonymous 13.09.2016 / 15:17

2 answers

4

I would do the following:

If you are sure that the default always includes "N" at the beginning:

string aux = linha.split(' ')[0];
string numeracao = aux.substring(1);

If you wanted an integer:

string aux = linha.split(' ')[0];
int numeracao = Int32.Parse(aux.substring(1));

If you have a text block and want to split the lines:

string[] separador = new string[] { "\r\n" };
string[] linhas = texto.Split(separador, StringSplitOptions.None);
foreach(string linha in linhas)
{
  string aux = linha.split(' ')[0];
  int numeracao = Int32.Parse(aux.substring(1));
}
    
13.09.2016 / 15:53
3

To open the file for reading you can use the File.OpenText ".

File.OpenText returns a StreamReader , assuming it is a multi-line file, use the StreamReader.ReadLine " to read row by line in a loop :

string linha;

using(var arquivo = File.OpenText("arquivo1.txt")) {
    while ((linha = arquivo.ReadLine()) != null) {
        // Use "linha" aqui ...
    }
}

To get the sequence before the first space, use the String.IndexOf :

string linha = "foo bar baz";
int indice = linha.IndexOf(" "); // 3. O número de caracteres antes do primeiro espaço

With the index of the characters you want to remove, use the String.Substring to return the sequence from that index:

string linha = "foo bar baz";
int indice = linha.IndexOf(" ");

string outraLinha = "bar" + linha.Substring(indice);

Console.WriteLine(linha);      // foo bar baz
Console.WriteLine(outraLinha); // bar bar baz

In your specific case, you can apply this way:

using System.IO;
// ...

string linha;
int contador = 0;

using(var arquivo = File.OpenText("foobar.txt")) { // Abre o arquivo para leitura
    while ((linha = arquivo.ReadLine()) != null) { // Lê linha por linha
        int espaco = linha.IndexOf(" "); // Quantidade de caracteres antes do espaço
        contador++; // Incrementa o número da linha atual
        // Retorna os caracteres a partir do primeiro espaço
        string linhaIndexada = "N" + contador + linha.Substring(espaco); 

        // Use "linhaIndexada" aqui ...
    }
}

See DEMO

    
13.09.2016 / 18:13