Reputation: 281
I am trying to split an array of strings where each of them have "," as the delimiter. I obtained the array of strings after an earlier split using regex for the pattern of new line. The input is from a text file and here is the pattern as in the text file.
Contents of my text file
"first", "second"
"third", "fourth", "fifth"
"Sixth", "seventh"
Second text file
"Color.auto", "(current == ff) && (current == 00)"
"Color.auto", "(current == ff) ? ((Current > 0) && (current < 10))"
The code which creates an array of strings split on new line character.
StreamReader sr = new stream reader(file.txt);
String data = sr.ReadToEnd();
String pattern = @"\r\n";
String[] result = regex.split(data, pattern);
foreach(string store in result)
{
String temp = store.split(",".ToCharArray());
}
The problem I am facing is that I am unable to split the strings on "," further using "split". I believe it is due to the array of strings which I am trying to split.
Upvotes: 2
Views: 245
Reputation: 79631
//Functional style
var tokens = File.ReadLines(file)
.SelectMany(line => line.Split(',')) //split lines on commas
.Select(token => token.Trim(' ')) //remove spaces around tokens
.Select(token => token.Trim('"')); //remove quotes around tokens
//Query style
var tokens = from line in File.ReadLines(file)
from token in line.Split(',')
select token.Trim(' ').Trim('"');
Note this will only work if your quoted strings in the file do not contain commas. If they do, you'll want to look into using regex.
Upvotes: 3
Reputation: 15397
Just use String.Split with the StringSplitOptions parameter:
string[] tokens = data.Split(new char[] { '\r', '\n', ',', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
This will take your single string and split it based on all linefeed parts as well as all commas. I threw in the space and tab character as well, though you can remove them if you don't want them.
The second parameter is so that you don't get empty tokens returned, e.g. between '\r'
and '\n'
.
EDIT Based on your second file, you don't want to remove whitespace, though it looks like you do probably want to remove the quotes. In that case, your line would be as follows. (I've split it into two lines just to make it look neater.)
char[] delimiters = new char[] { '\r', '\n', ',', '"' };
string[] tokens = data.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
Upvotes: 8