Link to home
Start Free TrialLog in
Avatar of DeveloperUser
DeveloperUserFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Split string C#

Hi,

I have the following string:  "50_100_5TH RED_PAR / DAR_TB" (which is a variable)

I would like to get the "50" and the "100" into 2 seperate strings.
Note that the seperators are "-" underscores

Any idea's?

Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

string s = "50_100_5TH RED_PAR / DAR_TB";
string[] words = s.Split('_');

string firstVariable = words[0];
string secondVariable = words[0];
ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Gene_Cyp
Gene_Cyp

I'm not posting to get points, just adding some comment to explain what dhaest gave you:

"50_100_5TH RED_PAR / DAR_TB"

will be split into:

50
100
5TH Red
PAR/DAR
TB

with positions in the array Words: 0-4

So, in the future when you need to do something like that again you'll know how to adapt it.
if they are only numbers you are trying to grab ,
execute the upper bound of words splitted array and
you can try cross  checking them as
CINT ( words[1]) , if they are integer the u can grab them
Amar
Dhaest solution works perfectly. But it allocates 5 strings :)

My code allocates two strings only - but more calculus is involved :)


string s = "50_100_5TH RED_PAR / DAR_TB";
            string firstVariable = s.Substring(0,s.IndexOf("_"));
            string secondVariable = s.Substring(firstVariable.Length + 1, s.IndexOf("_", firstVariable.Length+1) - firstVariable.Length - 1);
            MessageBox.Show(firstVariable + Environment.NewLine + secondVariable);

Open in new window

what do you want do exactly, can you please be precise
Amar
Avatar of DeveloperUser

ASKER

Perfect!