I am trying to split a string made of words, separated by the delimiter "-" and ",". The problem is that my program simply doesn't want to save anything in "var tokens". I already tried making "tokens" a string[], tried to use a char[] separator instead of putting "-" directly in the Split method, and tried the syntax "StringSplitOptions.RemoveEmptyEntries, but nothing works.
Here is my code:
if (!string.IsNullOrEmpty(destin) && string.IsNullOrEmpty(depar))
{
try
{
writer.WriteLine("SearchDest");
writer.WriteLine(destin);
string retur = reader.ReadLine();
Debug.WriteLine(retur);
var tokens = retur.Split('-');
flight.Clear();
foreach (string s in tokens)
{
Debug.WriteLine(s);
String[] flyelem = s.Split(',');
int idf = Convert.ToInt32(flyelem[0]);
String destf = flyelem[1];
String airf = flyelem[2];
int frees = Convert.ToInt32(flyelem[3]);
String datef = flyelem[4];
Flight b = new Flight(idf, destf, airf, frees, datef);
flight.Add(b);
}
dataGridView3.DataSource = null;
dataGridView3.Refresh();
dataGridView3.DataSource = flight;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The lines
string retur = reader.ReadLine();
Debug.WriteLine(retur);
will print: -6,Moscow,Domodedovo,30,4/3/2017 12:00:00 AM-7,Moscow,Vnukovo,30,4/3/2017 12:00:00 AM-9,Moscow,Vnukovo,40,4/3/2017 12:00:00 AM
and the line "Debug.WriteLine(s);" will always print nothing, just an empty space, the program stopping when it tries to parse the string to int at int idf.
How can I fix this problem and make split to work? Thank you.
EDIT: Problem fixed. Tommy Naidich suggestion regarding using new[] {'-'} and Gunther Fox one of using StringSplitOptions.RemoveEmptyEntries as the second argument worked, and now the split works as intended. Final code for people who will encounter this problem in the future. Thank you guys.
if (!string.IsNullOrEmpty(destin) && string.IsNullOrEmpty(depar))
{
try
{
writer.WriteLine("SearchDest");
writer.WriteLine(destin);
string retur = reader.ReadLine();
Debug.WriteLine(retur);
string[] output = retur.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
flight.Clear();
foreach (string s in output)
{
Debug.WriteLine(s);
string[] flyelem = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int idf = Convert.ToInt32(flyelem[0]);
string destf = flyelem[1];
string airf = flyelem[2];
int frees = Convert.ToInt32(flyelem[3]);
string datef = flyelem[4];
Flight b = new Flight(idf, destf, airf, frees, datef);
flight.Add(b);
}
dataGridView3.DataSource = null;
dataGridView3.Refresh();
dataGridView3.DataSource = flight;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}