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