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
Here's another approach:
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With