Split to separate part of a string considers first separator

3

I have the following text:

  

_2910_0908_401 _600_ERV__P_119552_GUARITA ERV WITHOUT ENERGY RADIO INOPERAN_TE SEMAFOROS P TRENS AND VEICLS OFF_PSG TREM C FLAG SIGN BY GUAR_ITA

I use Split to break every "_"

  itens = this.EntidadeMacro.Texto.Split('_');

Is there any way I can ignore the first "_" and start going from the second.

Example: My code is doing the following:

_
2910

and leaving this position empty.

and what I need and I'm trying to find a way to do and break from the 2nd "_":

_2910
0908
401

and so on ...

    
asked by anonymous 29.10.2014 / 13:39

3 answers

4

So I understand that the first character is guaranteed to be "_", so just treat the exception from the first part. You can do this:

using static System.Console;

public class Test {
    public static void Main() {
        string texto = "_2910_0908_401 _600_ERV__P_119552_GUARITA ERV SEM ENERGIA RADIO INOPERAN_TE SEMAFOROS P TRENS E VEICLS APAGADOS_PSG TREM C SINAL DE BANDEIRA PELA GUAR_ITA";
        string[] partes = texto.Substring(1).Split('_');
        partes[0] = "_" + partes[0];
        foreach(string parte in partes) WriteLine(parte);
    }
}

See running on .NET Fiddle . And no Coding Ground . Also put it in GitHub for future reference .

    
29.10.2014 / 14:10
2

Can you use LINQ? If so, this worked for me:

        Console.Clear();
        string teste = "_2910_0908_401 _600_ERV__P_119552_GUARITA ERV SEM ENERGIA RADIO INOPERAN_TE SEMAFOROS P TRENS E VEICLS APAGADOS_PSG TREM C SINAL DE BANDEIRA PELA GUAR_ITA";
        foreach(string t in teste.Split('_').Where(x => x != ""))
            Console.WriteLine(t);
        Console.ReadKey();
    
29.10.2014 / 13:54
2

Just be creative with the code;)

string foo = "_2910_0908_401 _600_ERV__P_119552_GUARITA ERV SEM ENERGIA RADIO INOPERAN_TE SEMAFOROS P TRENS E VEICLS APAGADOS_PSG TREM C SINAL DE BANDEIRA PELA GUAR_ITA";

int indiceDoPrimeiroUnderline = foo.IndexOf("_");
string primeiraParte = foo.Substring(0, (indiceDoPrimeiroUnderline + 1));
string resto = foo.Substring(indiceDoPrimeiroUnderline + 1);

string[] quebra = resto.Split(new char[] { '_' });
quebra[0] = primeiraParte + quebra[0];

Array quebra will contain all parts of the string broken by the character _ ... But the first element will be different, as if the first _ had not been considered for the break. Good luck!

    
29.10.2014 / 14:07