problems with string and split C#

Asked

Viewed 233 times

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 wanted something more generic, for example, if the user put "1-2-3-4-5", he also wanted the array to return {"1", "2", "3", "4", "5"}
in short, I just want the numbers of a string, no matter what’s between them.

  • Use the function split - str.Split(" ")

  • more I needed to figure out the spliter, like if the string was "1-2-3-4-5" assign to the spliter the "-"

  • Your question is not very clear as to what you want, try to make it clearer that it will be easier to find some help. :)

  • Now, what can there be between the numbers? Are they always the same characters? Can they be different characters in the same string?

  • 1

    may be different characters, I will try to make the question clearer

  • Do you want to separate by any character that is between the numbers? For example, if the string is "2+5-4a8s4", you want to get an array only with the numbers?

  • no, actually the string will only have numbers (some with comma) and the spliter (which I have no control, sometimes it is a space, sometimes it is a dash and so on)

  • 1

    I closed because the accepted answer does not match what the question is asking. If the question becomes clearer it is possible to reopen.

Show 3 more comments

2 answers

7


Can make a split using Regex, this way you can consider a pattern to separate the string.

Let’s consider that our pattern for separating is everything that is not a number except points (which may be among the numbers)

  • ^\d I consider anything but a number
  • &\. and here add the point 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 working

5

Try to do something where you take the first char from the spliter, but remember that you will always have to have the same characters throughout the string if it doesn’t, it doesn’t work!

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

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

Browser other questions tagged

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