我尝试在找到逗号时将一个字符串分割成单独的字符串变量。
string[] dates = line.Split(',');
foreach (string comma in dates)
{
string x = // String on the left of the comma
string y = // String on the right of the comma
}
我需要能够为逗号两边的字符串创建一个字符串变量。谢谢。
在这种情况下,摆脱ForEach。
只需要:
string x = dates[0];
string y = dates[1];
string y = dates.Length > 1 ? dates[1] : "";
- Shadow The Spring Wizardline
中的数据不正确,运行时错误可能比分配一些随机值要好。 - heijp06只需从数组中获取字符串:
string[] dates = line.Split(',');
string x = dates[0];
string y = dates[1];
string[] dates = line.Split(new char[]{','}, 2);
另一种选择是使用字符串操作:
int index = lines.IndexOf(',');
string x = lines.Substring(0, index);
string y = lines.Substring(index + 1);
string x = dates[0];
string y = dates[1];