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

What is the best way to split a string into two using a single char delimiter?

The string must be split into the first instance of the delimiter. The method should take into account performance. It should not assume that a separator exists in a string, that a string has any characters, etc .; should be a general purpose code, you can just connect to where you need to.

(I always need to rewrite such things for a few minutes when I need it, so I thought I asked a question)

+6
source share
4 answers

If you really want to have only two results, use the line splitting method with the second parameter:

string[] words = myString.Split(new char[]{' '}, 2); 
+8
source
 var part1 = myString.SubString(0, myString.IndexOf('')); var part2 = myString.SubString(myString.IndexOf(''), myString.Lenght); 
+3
source
  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; } 
0
source

(I always need to rewrite such things for a few minutes when I need it, so I thought I asked a question)

If you need this often, you can convert your preferred way of doing this into an extension method . Based on the offer of Theoman Soygul:

 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
source

Source: https://habr.com/ru/post/888755/


All Articles