Skip to content

Instantly share code, notes, and snippets.

@sinairv
Created December 17, 2011 15:51
Show Gist options
  • Save sinairv/1490549 to your computer and use it in GitHub Desktop.
Save sinairv/1490549 to your computer and use it in GitHub Desktop.
Utilities for Joining and Separating a Set of Strings with a Specified Separator Character
/// <summary>
/// Separates the given compound string assuming that string components are separated
/// with the given separator character.
/// It is assumed that any usage of the separator character inside the compound string
/// is escaped with a backslash character, and any usage of the backslash character
/// is escaped with double backslash characters.
/// </summary>
/// <param name="compound">The compound string</param>
/// <param name="separator">The separator character</param>
/// <returns><c>List</c> of strings that built the original compound string</returns>
public static List<string> SeparateAndUnescapeString(string compound, char separator)
{
var lstParts = new List<string>();
const char escapeChar = '\\';
int len = compound.Length;
var sb = new StringBuilder(len);
for(int i = 0; i < len; i++)
{
if (compound[i] == escapeChar) // unescape the next character
{
if (i + 1 < len)
{
sb.Append(compound[i + 1]);
i++;
}
else
// if backslash is comming in the end then put
// it in the resulting string as is
{
sb.Append(compound[i]);
}
}
else if(compound[i] == separator)
{
// time to separate
var curPart = sb.ToString().Trim();
if(!String.IsNullOrEmpty(curPart))
lstParts.Add(curPart);
sb = new StringBuilder(len - i);
}
else
{
sb.Append(compound[i]);
}
}
var lastPart = sb.ToString().Trim();
if (!String.IsNullOrEmpty(lastPart))
lstParts.Add(lastPart);
return lstParts;
}
/// <summary>
/// Joins the sequence of strings provided, separated by the provided separator
/// character. Any usage of the separator character and the backslash character
/// is escaped in the resulting compound string with backslash + separator, and
/// double backslashes respectively.
/// </summary>
/// <param name="strs">The sequence of strings to be joined</param>
/// <param name="separator">The separator character</param>
/// <returns>a compound string resulted from joining the sequence of strings
/// together.</returns>
public static string JoinAndEscapeStrings(IEnumerable<string> strs, char separator)
{
const char escapeChar = '\\';
string strEscape = escapeChar.ToString();
string strSeparator = separator.ToString();
var sb = new StringBuilder(100);
foreach (string str in strs)
{
var escapedStr = str.Replace(strEscape, strEscape + strEscape)
.Replace(strSeparator, strEscape + strSeparator);
if (!String.IsNullOrEmpty(escapedStr))
{
if (sb.ToString().Length > 0)
sb.Append(separator);
sb.Append(escapedStr);
}
}
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment