Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ProperCase to a sentence which is in Title Case (as opposed to sentence case)

Tags:

c#

Hello I'd like to convert a word which is in proper case to a sentence which is in title case. Example:

NumberOfLoyalHonestWomen would become

Number Of Loyal Honest Women

It's basically a way combined with reflection to turn Field / Property names into poor man's labels when auto-generating the inputs for a screen.

Here's what I got. Is there a better or cleaner way? Dot Net Fiddle

using System;
using System.Text.RegularExpressions;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string testString = "ATCPConnection";
        Console.WriteLine(testString.ToSentence());
    }

}

public static class StringExtensions
{
    public static string ToSentence(this string Source)
    {
        return Regex.Replace(string.Concat(from Char c 
                                           in Source.ToCharArray()
                                           select Char.IsUpper(c) ? " " + c : c.ToString()).Trim(), 
                             "(?<AcronymLetter>[A-Z]) (?=[A-Z](?![a-z]))", 
                             "${AcronymLetter}");
    }

}

Side Note: It was complicated by my desire to keep acronyms intact, hence the Regex.Replace. For example:

MGTOWSaysThereAreMoreUnicorns would become

MGTOW Says There Are More Unicorns

like image 329
toddmo Avatar asked Dec 19 '22 17:12

toddmo


1 Answers

Here's another approach:

  1. Insert a space before every uppercase letter which is immediately followed by a lowercase letter (except if this occurs at the beginning of the string). This adds spaces before PascalCased words.
  2. Then insert a space before every uppercase letter which is immediately preceded by a lowercase letter. This adds spaces before ACRONYMS.

Thus:

public static string ToSentence(this string Source)
{
    Source = Regex.Replace(Source, "((?<!^)[A-Z][a-z])", " $1");
    Source = Regex.Replace(Source, "([a-z])([A-Z])", "$1 $2");
    return Source;
}

UPDATE: The two regexes above can be combined into a one-liner:

public static string ToSentence(this string Source)
{
    return Regex.Replace(Source, "(?<!^)[A-Z][a-z]|(?<=[a-z])[A-Z]", " $0");
}
like image 83
Michael Liu Avatar answered May 20 '23 17:05

Michael Liu