How to separate a String according to a tab in C #?

6

I have a string in this format:

string valores = "Numero1#Numero2#Numero3#Numero4#";

How do I debit it in an integer array to get this:

int Numero[1] = Numero1;
int Numero[2] = Numero2;
int Numero[3] = Numero3;
int Numero[4] = Numero4;

I tried something like this but it did not roll:

cod_cg_meta_periodo.Split("#",System.StringSplitOptions.RemoveEmptyEntries);
    
asked by anonymous 02.05.2014 / 19:07

3 answers

10

You can use the string.Split method:

var array = valores.Split('#');

If you want to pass options, you have to do this:

var array = valores.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

Or when the separator is a more complex string:

var array = valores.Split(new string[] { "#" }, // lista de separadores complexos
                          StringSplitOptions.RemoveEmptyEntries);
    
02.05.2014 / 19:10
5

String Array

string valores = "numero1#numero2#numero3#numero4#";
string[] itemValores = valores.Split('#');

To read your positions

foreach (var item in itemValores)
{
    //item tem o valor de cada item da lista itemValores            
}

if (itemValores.Count() > 0)
{
   var str = itemValores[0];
}
    
02.05.2014 / 19:19
4

If the goal is to interpret the numbers in the string as integers, you can do the following:
To:

string valores = "1#2#3#4#";
int[] numeros;

Separate the string and create an array to store the numbers.

string[] numeros_str = valores.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
numeros = new int[numeros_str.Length];

Interprets the strings that contain the numbers.

for(int i = 0; i < numeros.Length; i++)
{
    numeros[i] = Int32.Parse(numeros_str[i]);
}

Another option, I believe is better, is, using LINQ:

string valores = "1#2#3#4#";
int[] numeros = valores.Split(new string[] {"#"}, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToArray();
    
02.05.2014 / 19:21