Friday, January 22, 2016

Split string by another string in C#

Normally developers use String.Split method to split a string by a character. An Overloaded version of same method can be used to split a string by string in C#.


string data = "THExxQUICKxxBROWNxxFOX"; 
return data.Split(new string[] { "xx" }, StringSplitOptions.None);

  • A string array should be passed as first parameter. 
  • In second parameter we can specify whether the substrings include empty array elements. etc
In this example string "xx" is passed but multiple string values can be passed as we want

string value = "The handsome, energetic, young dog was playing with his smaller, more lethargic litter mate."; 
string[] separators = {",", ".", "!", "?", ";", ":", " "}; 
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries); 
 foreach (var word in words) 
  Console.WriteLine(word);

more details can be found here.

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...