65.9K
CodeProject is changing. Read more.
Home

How to Toggle String Case in .NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.41/5 (9 votes)

Feb 9, 2011

CPOL
viewsIcon

204792

Shows how to toggle the contents of a string from upper case to lower, or vice versa

The following snippet shows how to toggle string casing in .NET:
public string ToggleCase(string input)
{
    string result = string.Empty;
    char[] inputArray = input.ToCharArray();

    foreach (char c in inputArray)
    {
        if (char.IsLower(c))
            result += c.ToString().ToUpper();
        else if (char.IsUpper(c))
            result += c.ToString().ToLower();
        else
            result += c.ToString();
    }

    return result;
}
This code snippet could be simplified as follows:
public string ToggleCase(string input)
{
    string result = string.Empty;
    char[] inputArray = input.ToCharArray();
    foreach (char c in inputArray)
    {
        if (char.IsLower(c))
            result += Char.ToUpper(c);
        else
            result += Char.ToLower(c);
    }
    return result;
}
But still performance of Alternate 1 and Alternate 2 is 2...3 times better than of this one: see the online comparative test at: http://webinfocentral.com/resources/toggleCaseAlgorithm.aspx[^] Regards, Alex Bell