Ad

How To Split A String Into Two Parts Using A Character Separator In C#?

- 1 answer

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)

Ad

Answer

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);
Ad
source: stackoverflow.com
Ad