开发者

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

开发者 https://www.devze.com 2023-03-08 01:32 出处:网络
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. I

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)


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


var part1 = myString.SubString(0, myString.IndexOf(''));
var part2 = myString.SubString(myString.IndexOf(''), myString.Lenght);


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


(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) };
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消