65.9K
CodeProject is changing. Read more.
Home

How to Toggle String Case in .NET

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 23, 2011

CPOL
viewsIcon

4764

Hi,Don`t know how to test its speed, but this does the trick and it also handles unicode. My aproach was to test for casing the least ammount of times as possible, I didn`t figure out how to group accented letters, for those it does it one at a time, so there is still room for improvement....

Hi, Don`t know how to test its speed, but this does the trick and it also handles unicode. My aproach was to test for casing the least ammount of times as possible, I didn`t figure out how to group accented letters, for those it does it one at a time, so there is still room for improvement. Also, I'm using a magic string for the pattern, this should be removed for maybe a constant or something else.
public static string ChangeCasing(string value)
        {
            StringBuilder sb = new StringBuilder();
            foreach (Match m in Regex.Matches(value, "([.\\d\\W]+)|([a-z]+)|([A-Z]+)|(?:\\P{M}\\p{M}*)"))
                sb.Append(char.IsLower(m.Value[0]) ? m.Value.ToUpper() : m.Value.ToLower());
            return sb.ToString();
        }