C# String Utils

Documenting a few simple string utils I created for an app recently

Be sure to resolve usings as needed

public static string SingleSpace(string str)
{
    //replaces multiple spaces with one.
    RegexOptions options = RegexOptions.None;
    Regex regex = new Regex(@"[ ]{2,}", options);
    str = regex.Replace(str, @" ");
    return str;
}

public static string SlashFlip(string source, int direction)
{
    string returnVal = null;
    if (direction == 0) //back
    {
        returnVal = source.Replace(@"/", @"\");
    }
    else if (direction == 1) //forward
    {
        returnVal = source.Replace(@"\", @"/");
    }
    return returnVal;
}

public static string SlashTrim(string str)
{
    if (str.IndexOf(@"/") == 0 || str.IndexOf(@"\") == 0) //first char
    {
        str = str.Substring(1, str.Length - 1);
    }
    if (str.IndexOf(@"/") == str.Length || str.IndexOf(@"\") == str.Length) //last char
    {
        str = str.Substring(str.Length, 1);
    }
    return str;
}

public static string IdXml(string[] idArray)
{
    string returnXml = null;
    List ids = new List(); //list of id's for the XmlSerializer
    foreach (string id in idArray)
    {
        ids.Add(Convert.ToInt64(id));
    }
    //create Xml doc from list to pass id's into sproc as a single param
    XmlSerializer xs = new XmlSerializer(typeof(List));
    MemoryStream ms = new MemoryStream();
    xs.Serialize(ms, ids);
    returnXml = UTF8Encoding.UTF8.GetString(ms.ToArray());

    return returnXml;
}

public static string StripDomain(string userIdentityName)
{
    //remove domain name and back slash if present
    int i = userIdentityName.IndexOf(@"\");
    if (i > -1) userIdentityName = userIdentityName.Remove(0, i + 1);
    return userIdentityName;
}
comments powered by Disqus