C#将字符串拆分为单独的变量

我发现在找到逗号时,我试图将字符串拆分为单独的字符串变量。

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[] 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];