根据字符的第一个匹配项拆分字符串

如何根据指定字符的第一个匹配项拆分 C # 字符串? 假设我有一个具有值的字符串:

101,a,b,c,d

我想把它分成

101
a,b,c,d

这是第一次出现逗号字符。

87832 次浏览

Use string.Split() function. It takes the max. number of chunks it will create. Say you have a string "abc,def,ghi" and you call Split() on it with count parameter set to 2, it will create two chunks "abc" and "def,ghi". Make sure you call it like string.Split(new[] {','}, 2), so the C# doesn't confuse it with the other overload.

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

You can specify how many substrings to return using string.Split:

var pieces = myString.Split(new[] { ',' }, 2);

Returns:

101
a,b,c,d

You can use Substring to get both parts separately.

First, you use IndexOf to get the position of the first comma, then you split it :

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

On the second part, the +1 is to avoid including the comma.

In .net Core you can use the following;

var pieces = myString.Split(',', 2);

Returns:

101
a,b,c,d
var pieces = myString.Split(',', 2);

This won't work. The overload will not match and the compiler will reject it.

So it Must be:

char[] chDelimiter = {','};
var pieces = myString.Split(chDelimiter, 2);