Capitalizing on C#names

Asked

Viewed 2,867 times

30

I have in my application given names in capital letters, for example: "JOSÉ DA SILVA". I would like to format as follows: "José da Silva". How to do?

3 answers

39


One way is by using method Totitlecase to capitalize on words in C#.

CultureInfo.CurrentCulture.TextInfo.ToTitleCase("JOSÉ DA SILVA".ToLower()); // retorna "José Da Silva"

The call ToLower the method is therefore necessary ToTitleCase does not capitalize all words in uppercase (he considers them acronyms).

The problem is that the word "Da" has also been capitalized. For these cases it follows a simple method that disregards certain exceptional words:

static string CapitalizarNome(string nome)
{
    string[] excecoes = new string[] { "e", "de", "da", "das", "do", "dos" };
    var palavras = new Queue<string>();
    foreach (var palavra in nome.Split(' '))
    {
        if (!string.IsNullOrEmpty(palavra))
        {
            var emMinusculo = palavra.ToLower();
            var letras = emMinusculo.ToCharArray();
            if (!excecoes.Contains(emMinusculo)) letras[0] = char.ToUpper(letras[0]);
            palavras.Enqueue(new string(letras));
        }
    }
    return string.Join(" ", palavras);
}
  • 2

    I would just add the words "and", "das", "dos".

  • @Augustomen made :)

  • And I would turn into Extension method, but that’s not the most important thing ;)

2

A very simple way to do this is by using Regex.Replace and replace all words with their title-case versions, except in some special cases, which will be placed in a normalization dictionary:

static void Main(string[] args)
{
    var result = Regex.Replace("dia dos pais", @"\b(\w)(\w*)\b", TitleCase);
}

// dicionário de normalização, com chaves que são case-insensitive
static readonly Dictionary<string, string> special
    = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
    {
        { "e", "e" },
        { "de", "de" },
        { "da", "da" },
        { "do", "do" },
        { "das", "das" },
        { "dos", "dos" },
    };

static string TitleCase(Match matchPalavra)
{
    // se for uma das palavras especiais
    string replacement;
    if (special.TryGetValue(matchPalavra.Value, out replacement))
        return replacement;

    // se não for uma palavra especial, faz title-case
    return matchPalavra.Groups[1].Value.ToUpper()
         + matchPalavra.Groups[2].Value.ToLower();
}

1

Conventions are more or less consensual, and can be expressed more universally as regular Expression. Step-by-step normalisation of a natural person’s proper name:

  1. ToTitleCase(nome), maíusculas initials, which can also be referred to as InitCap() in other languages or frameworks.

  2. For security a trim() or better still a Trim after replacing all multiple or exotic spaces with the single standard space, i.e. regex /\s+/gu by space.

  3. Let us not forget the junior, which strictly needs to be written also with capital initial and full text. Therefore: replace / (?:jr\.?|j[uú]nior)$/i for " Júnior".

  4. The "e" alone, replace all the " E " for " e ".

  5. The other prepositions, / (d)([eao]|[ao]s) /gi for " d\2 ".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.