Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into two parts using a character separator in c#?

What's the best way to split a string into just two parts using a single-char separator?

The string should be split on the first instance of the separator. The method should consider performance. It shouldn't assume that the separator exists in the string, that the string has any characters, etc; should be general-purpose code you can just plug in wherever you need.

(It always takes me a few minutes to rewrite this sort of thing whenever I need it, so I thought I'd make a question for it)

like image 643
Rory Avatar asked May 22 '11 13:05

Rory


2 Answers

If you really want to have just two results, use the string split method with a 2nd parameter:

string[] words = myString.Split(new char[]{' '}, 2);
like image 177
slfan Avatar answered Nov 20 '22 22:11

slfan


var part1 = myString.SubString(0, myString.IndexOf(''));
var part2 = myString.SubString(myString.IndexOf(''), myString.Lenght);
like image 36
Teoman Soygul Avatar answered Nov 20 '22 22:11

Teoman Soygul