Split to separate part of a string considers first separator

Asked

Viewed 13,033 times

3

I have the following text::

_2910_0908_401 _600_ERV__P_119552_GUARITA ERV WITHOUT POWER RADIO INOPERAN_TE SEMAFOROS P TRENS AND VEICLS APAGADOS_PSG TRAIN C FLAG SIGNAL BY GUAR_ITA

there use the 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 ...

3 answers

5


From what I understand it is guaranteed that the first character is "_", so just treat the exception of 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);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

2

Can you use LINQ? If you can, it 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();
  • I get it, I can’t use LINQ !

  • 1

    @user2254936 E because you cannot use LINQ?

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];

The 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!

Browser other questions tagged

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