From 929398767d41b2af181cde259a585fc5aaf8f027 Mon Sep 17 00:00:00 2001 From: jcasteele Date: Thu, 1 Oct 2020 21:39:14 -0500 Subject: [PATCH] Update ToTitleCase.cs Creates better title case representation so that articles and prepositions shorter than 4 characters remain lowercase --- src/Humanizer/Transformer/ToTitleCase.cs | 26 +++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Humanizer/Transformer/ToTitleCase.cs b/src/Humanizer/Transformer/ToTitleCase.cs index 92111d4dc..7318beffa 100644 --- a/src/Humanizer/Transformer/ToTitleCase.cs +++ b/src/Humanizer/Transformer/ToTitleCase.cs @@ -9,11 +9,22 @@ public string Transform(string input) { var result = input; var matches = Regex.Matches(input, @"(\w|[^\u0000-\u007F])+'?\w*"); + + //While these arrays could be combined into a single array or list, they are kept separate to make list localization easier + string[] articleList = { "a", "an", "the" }; + string[] prepositionList = { "at", "as", "but", "by", "for", "in", "of", "off", "on", "out", "per", "til", "to", "up", "via" }; + foreach (Match word in matches) { if (!AllCapitals(word.Value)) { - result = ReplaceWithTitleCase(word, result); + if (!WordCheck(word.Value, articleList)) + { + if (!WordCheck(word.Value, prepositionList)) + { + result = ReplaceWithTitleCase(word, result); + } + } } } @@ -25,6 +36,19 @@ private static bool AllCapitals(string input) return input.ToCharArray().All(char.IsUpper); } + private static bool WordCheck(string input, string[] wordList) + { + bool wordMatch = false; + + for (int i = 0; i > wordList.Length; i++) + { + if (input == wordList[i]) + wordMatch = true; + } + + return wordMatch; + } + private static string ReplaceWithTitleCase(Match word, string source) { var wordToConvert = word.Value;