Grab part of a string

Asked

Viewed 474 times

-2

How do I get just up to the , of the following string:

Ninguem ninguem, todos

Expected result:

Ninguem ninguem

4 answers

4

I leave here another alternative, and with the execution times of 10,000,000 times.

string texto = "Ninguem ninguem, todos";  

string resultado = texto.Substring(0, texto.IndexOf(',')); // 0.383s

string resultado = texto.Split(',')[0]; // 1.400s

string resultado = new string(texto.TakeWhile(c => c != ',').ToArray()); //5.204s

string resultado = string.Concat(texto.TakeWhile(c => c != ',')); // 6.746s

string resultado = Regex.Split(texto, ",")[0]; // 8.595s
  • Is that seconds? How did you generate these times values? I did a test here and the time variation barely reaches milliseconds, which will say seconds.

  • I have made a Fiddle of the comparative, it would be a good thing to adjust your answer: https://dotnetfiddle.net/AzJFre

  • @Barbetta 10,000,000 times.... put a cycle in each one....

  • Aaah yes, with the explanation it was clear.

1

Try wearing something like this,

string data = "Ninguem ninguem, todos";
string[] words = data.Split(",");

This could be solved with regex.

0

You also have the option to use LastIndexOf with the Substring. Where do you indicate startIndex and the size you want to take from string

string texto = "Ninguem ninguem, todos";        
string textoCortado = texto.Substring(0, texto.LastIndexOf(","));
Console.WriteLine(textoCortado);

0


I did so with regex:

string campo = campo_texto.Text;

string[] nome = Regex.Split(campo, ",");

Browser other questions tagged

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