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

Bal*_*i C 7 c# string split

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

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
}
Run Code Online (Sandbox Code Playgroud)

我需要能够在逗号的每一侧为字符串创建一个字符串变量.谢谢.

Lar*_*ech 10

在这种情况下摆脱ForEach.

只是:

string x = dates[0];
string y = dates[1];
Run Code Online (Sandbox Code Playgroud)


Guf*_*ffa 8

只需从数组中获取字符串:

string[] dates = line.Split(',');
string x = dates[0];
string y = dates[1];
Run Code Online (Sandbox Code Playgroud)

如果可能有多个逗号,则应指定您只需要两个字符串:

string[] dates = line.Split(new char[]{','}, 2);
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用字符串操作:

int index = lines.IndexOf(',');
string x = lines.Substring(0, index);
string y = lines.Substring(index + 1);
Run Code Online (Sandbox Code Playgroud)