splitting a string into an array ... where a ' is involved...
I have a string like this:
"'IRE','ENG','SCO','WAL'"
And I want to put it into an array like this:
string[] countries = codesList.Split("','");
Well thats the idea anyway but I can't get it to split, nor can I just replace the char ' . Any ideas?
actually, you'd want
string[] countries = codesList.Split(',');
You want to split on the character comma, not the string comma.
Then you want to remove the single-quotes:
for(int i =0; i < countries.Length; ++i)
countries[ i ] = countries[ i ].Trim('\''); // That's single-quote, back-slash, single-quote, single-quote.
Well, you could add two more lines after your split to remove first ' from first element and last ' from last element:
countries[0] = countries[0].Substring(1, countries[0].Length - 1);
countries[countries.Length - 1] = countries[countries.Length - 1].Substring(0, countries[countries.Length - 1].Length - 1);
separators[] string = new string[] {"','"}
string[] countries = codesList.Split(separators, StringSplitOptions.None);to remove first and last single quotas, you can do, like this:
codesList = codesList.Substring(1, codesList.Length - 2)
separators[] string = new string[] {"','"}
string[] countries = codesList.Split(separators, StringSplitOptions.None);
OR
separators[] string = new string[] {"','", "'"}
string[] countries = codesList.Split(separators, StringSplitOptions.None);
but with this last method you have in countries empty strings in the first and last position...
you can remove this with
StringSplitOptions.RemoveEmptyEntries
but this remove also empty strings in the middle...
In the end I opted for
arrayList1.AddRange(countryList.Replace( "'", null).Split("','".ToCharArray()));
foreach (string strItem in Regex.Split("YourString", "YourDelim")){
Console.Writeline(strItem);
}
| foreach (string strItem in Regex.Split("YourString", "YourDelim")) |
|
It's not quite that simple (but, also, it's a bit simpler
)
First of all, using Regex.Split to divide on a simple delimiter is overkill. It would be faster to use String.Split. Regex.Split is design to accept a regular expression as the delimiter, so that could cause trouble if your delimiter contains a regex pattern code (such as a period) in it.
Next, we have to think about what exactly is the delimiter in this case. If you say just "comma", then we get strings that start & end with a single-quote. If we use "single-quote, comma, single-quote", we are still left with single-quotes at the beginning of the first, and at the end of the last. Plus, we completely miss division where it was inadvertantly written as "single-quote, comma, space, single-quote" (you know there's gonna be one).
U can try this...............
string compStr = "'IRE','ENG','SCO','WAL'";
string[] countries = new string[4];
countries = compStr.Split(new char[] { ',' }, 4);
foreach (string country in countries)
{
Console.WriteLine(country.Trim(new char[] {'\'' }));
}