We help IT Professionals succeed at work.

Split string C#

DeveloperUser
on
400 Views
Last Modified: 2012-05-11
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?

Comment
Watch Question

Dirk HaestProject manager
CERTIFIED EXPERT

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

string firstVariable = words[0];
string secondVariable = words[0];
Project manager
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
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
anarki_jimbelSenior Developer
CERTIFIED EXPERT

Commented:
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

Author

Commented:
Perfect!
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.