I\'d like to write an extension method for the .NET String class. I\'d like it to be a special varation on the Split method - one that takes an escape character to prevent s
Personally I'd cheat and have a peek at string.Split using reflector... InternalSplitOmitEmptyEntries
looks useful ;-)
Here is solution if you want to remove the escape character.
public static IEnumerable<string> Split(this string input,
string separator,
char escapeCharacter) {
string[] splitted = input.Split(new[] { separator });
StringBuilder sb = null;
foreach (string subString in splitted) {
if (subString.EndsWith(escapeCharacter.ToString())) {
if (sb == null)
sb = new StringBuilder();
sb.Append(subString, 0, subString.Length - 1);
} else {
if (sb == null)
yield return subString;
else {
sb.Append(subString);
yield return sb.ToString();
sb = null;
}
}
}
if (sb != null)
yield return sb.ToString();
}
public static string[] Split(this string input, string separator, char escapeCharacter)
{
Guid g = Guid.NewGuid();
input = input.Replace(escapeCharacter.ToString() + separator, g.ToString());
string[] result = input.Split(new string []{separator}, StringSplitOptions.None);
for (int i = 0; i < result.Length; i++)
{
result[i] = result[i].Replace(g.ToString(), escapeCharacter.ToString() + separator);
}
return result;
}
Probably not the best way of doing it, but it's another alternative. Basically, everywhere the sequence of escape+seperator is found, replace it with a GUID (you can use any other random crap in here, doesn't matter). Then use the built in split function. Then replace the guid in each element of the array with the escape+seperator.
The signature is incorrect, you need to return a string array
WARNIG NEVER USED EXTENSIONs, so forgive me about some errors ;)
public static List<String> Split(this string input, string separator, char escapeCharacter)
{
String word = "";
List<String> result = new List<string>();
for (int i = 0; i < input.Length; i++)
{
//can also use switch
if (input[i] == escapeCharacter)
{
break;
}
else if (input[i] == separator)
{
result.Add(word);
word = "";
}
else
{
word += input[i];
}
}
return result;
}