From 90cab3af3471752b7f7ca2224d15f514c69c40fa Mon Sep 17 00:00:00 2001 From: Mahdi Hosseini Date: Fri, 11 Jun 2021 15:24:56 +0430 Subject: [PATCH] Update ToTitleCase.cs --- .../Internals/Transformer/ToTitleCase.cs | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/Shared/HandyControl_Shared/HandyControls/Tools/Extension/Internals/Transformer/ToTitleCase.cs b/src/Shared/HandyControl_Shared/HandyControls/Tools/Extension/Internals/Transformer/ToTitleCase.cs index 5f8faf680..3b3e37bdd 100644 --- a/src/Shared/HandyControl_Shared/HandyControls/Tools/Extension/Internals/Transformer/ToTitleCase.cs +++ b/src/Shared/HandyControl_Shared/HandyControls/Tools/Extension/Internals/Transformer/ToTitleCase.cs @@ -1,4 +1,5 @@ -using System.Globalization; +using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text.RegularExpressions; @@ -17,12 +18,14 @@ public string Transform(string input, CultureInfo culture) var result = input; var matches = Regex.Matches(input, @"(\w|[^\u0000-\u007F])+'?\w*"); + var firstWord = true; foreach (Match word in matches) { if (!AllCapitals(word.Value)) { - result = ReplaceWithTitleCase(word, result, culture); + result = ReplaceWithTitleCase(word, result, culture, firstWord); } + firstWord = false; } return result; @@ -33,10 +36,28 @@ private static bool AllCapitals(string input) return input.ToCharArray().All(char.IsUpper); } - private static string ReplaceWithTitleCase(Match word, string source, CultureInfo culture) + private static string ReplaceWithTitleCase(Match word, string source, CultureInfo culture, bool firstWord) { + var articles = new List { "a", "an", "the" }; + var conjunctions = new List { "and", "as", "but", "if", "nor", "or", "so", "yet" }; + var prepositions = new List { "as", "at", "by", "for", "in", "of", "off", "on", "to", "up", "via" }; + var wordToConvert = word.Value; - var replacement = culture.TextInfo.ToUpper(wordToConvert[0]) + culture.TextInfo.ToLower(wordToConvert.Remove(0, 1)); + string replacement; + + + if (firstWord || + (!articles.Contains(wordToConvert) && + !conjunctions.Contains(wordToConvert) && + !prepositions.Contains(wordToConvert))) + { + replacement = culture.TextInfo.ToUpper(wordToConvert[0]) + culture.TextInfo.ToLower(wordToConvert.Remove(0, 1)); + + } + else + { + replacement = culture.TextInfo.ToLower(wordToConvert); + } return source.Substring(0, word.Index) + replacement + source.Substring(word.Index + word.Length); } }