Multiple Delimiter in a single string! How to count those as one?

  • Thread starter Thread starter pengb
  • Start date Start date
P

pengb

Hello All:
A pretty frustrating question to ask! I use the string [] something
= stringx.split (delimiter.tochararray()) mathod to delimit a long
string by space! So supposely
if the stringx is :
" something something1 something2 " I should get string [0] =
something, string[1] = something1...etc
However question comes what happens if the string looks like this
" something something1 something 2"
instead of string [0] = something, string[1] = something1...

I get string [0] = something string[1] = "" string[2] =
""........string[11] = something1....etc

In excel there is a function in text delimiter to treat all similar
delimiter as one. I just wondering how to do that in C#?

Thank You For your reply!
 
Hello All:
A pretty frustrating question to ask! I use the string [] something
= stringx.split (delimiter.tochararray()) mathod to delimit a long
string by space! So supposely
if the stringx is :
" something something1 something2 " I should get string [0] =
something, string[1] = something1...etc
However question comes what happens if the string looks like this
" something something1 something 2"
instead of string [0] = something, string[1] = something1...

I get string [0] = something string[1] = "" string[2] =
""........string[11] = something1....etc

In excel there is a function in text delimiter to treat all similar
delimiter as one. I just wondering how to do that in C#?

You can use RegularExpressions to do this.... pretty simple really:

string s = "something something somethingelse";
string[] ss = System.Text.RegularExpressions.Regex.Split(s, @"\s+");

-mdb
 
pengb said:
Hello All:
A pretty frustrating question to ask! I use the string [] something
= stringx.split (delimiter.tochararray()) mathod to delimit a long
string by space! So supposely
if the stringx is :
" something something1 something2 " I should get string [0] =
something, string[1] = something1...etc
However question comes what happens if the string looks like this
" something something1 something 2"
instead of string [0] = something, string[1] = something1...

I get string [0] = something string[1] = "" string[2] =
""........string[11] = something1....etc

In excel there is a function in text delimiter to treat all similar
delimiter as one. I just wondering how to do that in C#?

Checking the docs, I see that the string.split method has several
overloads. One of them takes a StringSplitOptions enum:

string[] sa = s.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top