Skip to content

Commit

Permalink
Update ToTitleCase.cs
Browse files Browse the repository at this point in the history
  • Loading branch information
ghost1372 committed Jun 11, 2021
1 parent d2c36d5 commit 90cab3a
Showing 1 changed file with 25 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Globalization;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;

Expand All @@ -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;
Expand All @@ -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<string> { "a", "an", "the" };
var conjunctions = new List<string> { "and", "as", "but", "if", "nor", "or", "so", "yet" };
var prepositions = new List<string> { "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);
}
}
Expand Down

0 comments on commit 90cab3a

Please sign in to comment.