Just Split
by space and remove empty entries with using StringSplitOptions
var words = line.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
题
I'm reading in a file, which has 4 words per line. I want to grab each word and put into a string array. I thought the space between each word was a tab so I tried using the Split method to split the line whenever it sees a tab. But the space between the words is more than a tab, how do I tell the split method to do it this way?
Relevant part of code:
using (StreamReader sr = new StreamReader(file))
{
string line = sr.ReadToEnd();
var words = line.Split(new Char[] {'\t'}); //Does not work..
return words;
}
解决方案
Just Split
by space and remove empty entries with using StringSplitOptions
var words = line.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
其他提示
Add 'StringSplitOptions.RemoveEmptyEntries' to the Split parameter list
{
string line = sr.ReadToEnd();
var words = line.Split(new Char[] {'\t'}, StringSplitOptions.RemoveEmptyEntries);
return words;
}
If there are other characters between your numbers, not just the \t, then in you can specify more than one split character in the split list.
var words = line.Split(new Char[] {'\t', ' ','_'.......}, StringSplitOptions.RemoveEmptyEntries);
Well if you don't have idea about number of spaces then you have find someother way like, split with space and then remove spaces from strings
var words = line.Split(' ');
for(int i=0;i<words.length;i++)
words[i].Replace(" ",string.empty);
Or
var words = line.Split.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);