views:

509

answers:

4

I want to separate a string consisting of one or more two-letter codes separated by commas into two-letter substrings and put them in a string array or other suitable data structure. The result is at one point to be databound to a combo box so this needs to be taken into account.

The string I want to manipulate can either be empty, consist of two letters only or be made up by multiple two-letter codes separated by commas (and possibly a space).

I was thinking of using a simple string array but I'm not sure if this is the best way to go.

So... what data structure would you recommend that I use and how would you implement it?

+2  A: 

If you are simply going to bind to the structure then a String[] ought to be fine - if you need to work with the data before you use it as a data source then a List<String> is probably a better choice.

Here is an example:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
     String s = "ab,cd,ef";

     // either a String[]
     String[] array = s.Split(new Char[] {','});
     // or a List<String>
     List<String> list = new List<String>(s.Split(new Char[] { ',' }));
    }
}
Andrew Hare
+10  A: 

Definitely at least start with a string array, because it's the return type of string.Split():

string MyCodes = "AB,BC,CD";
char[] delimiters = new char[] {',', ' '};
string[] codes = MyCodes.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

Update: added space to the delimiters. That will have the effect of trimming spaces from your result strings.

Joel Coehoorn
oooh, learned something new...
Jason Lepack
This looks very promising :) Will try it tomorrow...
Sakkle
+3  A: 

My answer is "right", but I suggest Joel Coehoorn's answer.

public static string[] splitItems(string inp)
{
    if(inp.Length == 0)
     return new string[0];
    else
     return inp.Split(',');
}
Jason Lepack
+5  A: 

Would something like this work?

var list = theString.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
benrwb
+1 for the much more elegant ", ".ToCharArray(), I've been doing new char[]{',', ' '}
John Rasch
Shorter, yes. I don't know if it's more elegant. It's not much different in terms of how expressive it is, and will it be expanded at compile time or does that inject extra instructions that must be executed at runtime?
Joel Coehoorn
The ", ".ToCharArray() could be the initialiser for a static field, and avoid any chance of (or appearance of) repeated execution.
Richard