Reputation: 184
public void LoadWorldMap()
{
string path = "..\\Bin\\Assets\\WorldMap\\WorldMap.txt";
//Open the file and read it.
string[] fileText = File.ReadAllLines(path);
for (int index = 0; index < 320; index++)
{
string line = fileText[index];
string[] tokens = line.Split(' ');
System.Console.WriteLine(tokens[0]);
}
}
The file looks like this:
0 0 0 0 0
0 1 0 0 0
0 2 0 0 0
0 3 0 0 0
0 4 0 0 0
0 5 0 0 0
No commas, which is why it is
line.Split(' ');
However, when I output tokens[0] it is the entire line, not split. tokens[1] to tokens[4] is empty.
What am I doing wrong?
Upvotes: 0
Views: 88
Reputation: 33
As user2948630 mentioned the space character could be a tabbed space. It could also be a non breaking space if you copied text from a web page, or some other non printable character. To make sure the split character works for all possible spaces you could use a regular expression. For example,
string[] tokens = Regex.Split(line, @"\s+");
The \s metacharacter is used to find a whitespace character.
A whitespace character can be a:
The + will find one or more occurrences of a whitespace character.
Upvotes: 1
Reputation: 6374
As others noted the chars between the numbers are not spaces, but space like chars. The following regex will split the number tokens correctly regardless of what space type char is in the line.
string[] tokens = Regex.Split(line, @"\s+");
Upvotes: 0