Split strings

  • Thread starter Thread starter Tem
  • Start date Start date
T

Tem

What would be the best way to split a string into a string array. with the
following possible inputs?

abc1 abc2 abc3 -single space
abc1 abc2 abc3 -multiple spaces
abc1,abc2,abc3 -comma
abc1, abc2, abc3 -comma + space
abc1;abc2;abc3 -semicolon
abc1; abc2; abc3 -semicolon + space

Thanks

Tem
 
Tem said:
What would be the best way to split a string into a string array. with the
following possible inputs?

abc1 abc2 abc3 -single space
abc1 abc2 abc3 -multiple spaces
abc1,abc2,abc3 -comma
abc1, abc2, abc3 -comma + space
abc1;abc2;abc3 -semicolon
abc1; abc2; abc3 -semicolon + space


string[] pieces = theString.Split(new char[]{' ',',',';'},
StringSplitOptions.RemoveEmptyEntries);
 
Here is one way:

string s = "ab, cd;ef gg";
string[] array = s.Split(" ,;".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
foreach(string el in array)
Console.WriteLine("{0} count:{1}",el, el.Length);
W
 
What would be the best way to split a string into a string array.
with the following possible inputs?

abc1 abc2 abc3 -single space
abc1 abc2 abc3 -multiple spaces
abc1,abc2,abc3 -comma
abc1, abc2, abc3 -comma + space
abc1;abc2;abc3 -semicolon
abc1; abc2; abc3 -semicolon + space


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

or:

using System.Text.RegularExpressions;
string[] pieces = Regex.Split(theString, "[ ,;]+");

although both of these will also split things with any number (1 or more)
of any of the three characters (space, comma, semicolon), not just the
specific examples you list.

-mdb
 

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