根据第一次出现的字符拆分字符串

Vis*_*u Y 50 .net c# asp.net string

如何根据指定字符的第一次出现拆分C#字符串?假设我有一个值为"101,a,b,c,d"的字符串.我想把它拆分为101&a,b,c,d.这是第一次出现逗号字符.

Gra*_*ICA 121

您可以使用以下命令指定要返回的子字符串数string.Split:

var pieces = myString.Split(new[] { ',' }, 2);
Run Code Online (Sandbox Code Playgroud)

返回:

101
a,b,c,d
Run Code Online (Sandbox Code Playgroud)


Ari*_*ian 17

string s = "101,a,b,c,d";
int index = s.IndexOf(',');
string first =  s.Substring(0, index);
string second = s.Substring(index + 1);
Run Code Online (Sandbox Code Playgroud)

  • @pcnThird我没有downvote但可能是因为它只是代码而没有解释所使用的方法. (4认同)
  • 也许是因为如果IndexOf找不到分隔符,则返回-1.在这种情况下,代码将无法正确分割字符串.它应该首先返回整个字符串,但首先是空的(或者可能是崩溃). (3认同)

dot*_*NET 9

使用string.Split()功能。它需要最大值。它将创建的块数。假设您有一个字符串“abc,def,ghi”,并且您在参数设置为2的情况下对其调用Split() count,它将创建两个块“abc”和“def,ghi”。确保您将其命名为string.Split(new[] {','}, 2),以便 C# 不会将其与其他重载混淆。


Pie*_*ult 6

您可以Substring单独使用这两个部件.

首先,您使用IndexOf获取第一个逗号的位置,然后将其拆分:

string input = "101,a,b,c,d";
int firstCommaIndex = input.IndexOf(',');

string firstPart = input.Substring(0, firstCommaIndex); //101
string secondPart = input.Substring(firstCommaIndex + 1); //a,b,c,d
Run Code Online (Sandbox Code Playgroud)

在第二部分,+1是避免包括逗号.

  • 不要使用这个;如果从未找到逗号,firstCommaIndex 可以为 -1。 (2认同)