8

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)

4 Answers 4

8

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);
Sign up to request clarification or add additional context in comments.

4 Comments

That may return more than two parts, not a string split into two.
I added another version of String.split which might do the trick.
Oh yeah, I always forget about that version of Split() - that's exactly what I want.
Actually, there's no override with (String, int), you have to do myString.Split(new char[]{' '},2) ?
3
var part1 = myString.SubString(0, myString.IndexOf(''));
var part2 = myString.SubString(myString.IndexOf(''), myString.Lenght);

4 Comments

I would first check for the character, to prevent an exception on -1 on your second line of code.
True, I'm simply assuming that he knows the char exists beforehand.
I can't assume that the char exists beforehand; that's part of what makes this not a completely non-trivial question. Also performance-wise this calculates IndexOf twice, which for a large string may be significant (albeit small). Also I think part2 will contain the separator character.
Just a snippet, you can always modify like caching the index with 'var index = myString.IndexOf('');' etc.
0
    string[] SplitStringInTwo(string input, char separator)
    {
        string[] results = new string[2];
        if (string.IsNullOrEmpty(input)) return results;
        int splitPos = input.IndexOf(separator);
        if (splitPos <= 0) return results;
        results[0] = input.Substring(0, splitPos);
        if (splitPos<input.Length)
            results[1] = input.Substring(splitPos + 1);
        return results;
    }

3 Comments

why do all this when there is already a method like slfan points out.
@Roopesh: What if the split character occur more than once?
@Karlsen - there's an option for that. Check slfan's updated reply.
0

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

If you need this frequently, you could convert your preferred way of doing it into an extension method. Based on Teoman Soygul's suggestion:

public static class StringExtensions
{
  public static string[] TwoParts(this String str, char splitCharacter)
  {
    int splitIndex = str.IndexOf(splitCharacter);
    if(splitIndex == -1)
      throw new ArgumentException("Split character not found.");

    return new string[] {
      str.SubString(0, splitIndex),
      str.SubString(splitIndex, myString.Lenght) };
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.