Split string based on the first occurrence of the character Split string based on the first occurrence of the character asp.net asp.net

Split string based on the first occurrence of the character


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

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

Returns:

101a,b,c,d


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 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); //101string secondPart = input.Substring(firstCommaIndex + 1); //a,b,c,d

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