Split string based on the first occurrence of the character

How can I split a C# string based on the first occurrence of the specified character?
Suppose I have a string with value:

101,a,b,c,d

I want to split it as

101
a,b,c,d

That is by the first occurrence of comma character.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

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

Returns:

101
a,b,c,d

Method 2

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

Method 3

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.

Method 4

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.

Method 5

In .net Core you can use the following;

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

Returns:

101
a,b,c,d

Method 6

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);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x