Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

String Extensions - C#

RSS
Modified on Thu, Jun 18, 2020, 12:21 PM by Administrator Categorized as ·Net Framework

Code

public static class StringExtensions
{
    public static string ToProperCase(this string text)
    {
        string result = "";
        char apos = (char)39;

        for (int i = 0; i < text.Length; i++)
        {
            string s = text[i].ToString();
            if (i == 0 || (!char.IsLetter(text[i - 1]) & text[i - 1] != apos))
                result += s.ToUpper();
            else
                result += s;
        }
        return result;
    }
    /// <summary>
    /// Takes a Proper-Cased variable name and adds a space before each
    /// capital letter.
    /// </summary>
    public static string AddSpaces(this string text)
    {
        // Special case: if input is all UPPERCASE, add no spaces
        if (text == text.ToUpperInvariant())
            return text;

        var result = string.Empty;

        for (int i = 0; i < text.Length; i++)
        {
            // If we have multiple upper-case in a row, insert a space only before the last one
            if (i > 0 && char.IsUpper(text[i]) && (i == text.Length - 1 || char.IsLower(text[i - 1]) || char.IsLower(text[i + 1])))
                result += " ";

            result += text.Substring(i, 1);
        }
        return result;
    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.