problems with string and split C # [closed]

1

I have the following function:

string str = "1 2 3 4 5"; //string para separar
string[] ArrayValor = str.Split(" ");
//nesse caso o array seria {"1","2","3","4","5"}

But I wanted something more generic, for example, if the user entered "1-2-3-4-5", also wanted the array to return {"1", "2", "3", "4" , "5"}
in short, I want only the numbers of a string, no matter what is between them.

    
asked by anonymous 18.07.2017 / 22:09

2 answers

7

You can split using Regex , this way you can consider a pattern for separating the string.

Let's consider that our pattern for separating is anything but a number except points (which can be between numbers)

  • ^\d I consider everything other than a number
  • &\. and here I add the dot as "exception"

Example:

var regexp = new Regex(@"[^\d&\.]");
var valor = "4.5+8-8d5+5.4";
var arrNumeros = regexp.Split(valor);
//arrNumeros = ["4.5", "8, "8", "5", "5.4"];

See the fiddle

    
18.07.2017 / 22:45
5

Try to do something where you get the first char of the spliter, but remembering that you always have to have the same characters throughout the string if not, it does not work!

Note: The string must follow a pattern always with the first letter followed by the "spliter" and keep the same char of the spliter for the entire string. You can greatly improve the code with validations, there goes your taste! Remembering this is just an idea, not something concrete!

    string str = "1 2 3 4 5";
    string spliterType = str.Substring(1, 1);
   var strSplited = str.Split(Convert.ToChar(spliterType));
    
18.07.2017 / 22:29