如何根据首次出现的指定字符拆分C#字符串?假设我有一个带有值的字符串:
101,a,b,c,d
我想将其拆分为
101
a,b,c,d
那是第一次出现逗号字符。
Answers:
string s = "101,a,b,c,d";
int index = s.IndexOf(',');
string first = s.Substring(0, index);
string second = s.Substring(index + 1);
您可以用来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
在第二部分,+1避免包含逗号。