Pergunta

i want to validate a field of names in c#. My objective is to upper case the first letters of name and last names but keep the prepositions (in my language there are prepositions like "de", "da", "dos" in names) in lower case. I made something, but the problem is that i'm using Replace(), and it happens that, if a name starts with "l", every "l" will be big, for example:

"lake like de lol" will be "Lake Like de LoL"

private string nome;

        public string Nome
        {
            get { return nome; }
            set 
            {
                value = value.ToLower();
                value = value.Replace(value[0].ToString(), value[0].ToString().ToUpper());
                for (int i = 0; i < value.Length; i++)
                {
                    if (value[i].ToString() == " " && String.Concat(value[i + 1], value[i + 2], value[i + 3]) != "de " && String.Concat(value[i + 1], value[i + 2], value[i + 3]) != "da " && String.Concat(value[i + 1], value[i + 2], value[i + 3]) != "dos " && String.Concat(value[i + 1], value[i + 2], value[i + 3]) != "das " && String.Concat(value[i + 1], value[i + 2], value[i + 3]) != "  ")
                    {
                        value = value.Replace(value[i + 1].ToString(), value[i + 1].ToString().ToUpper());
                    }
                }

                nome = value;
            }
        }

Do anyone knows a solution for this? thanks and sorry for bad english!

Foi útil?

Solução

You could split your string into a string array using slip method and then for each string in this array to check if it's a preposition and if it's not to replace only first letter with it's upper case (You could subtract 32 from the char if it's between 97 and 122 - lower case Ascii characters)

Outras dicas

Here's an example that I wrote for you that uses a list of words to not capitalize.

class Program
{
    static List<string> listOfPrepositions = new List<string>()
        {
            "de",
            "da",
            "dos"
        };

    static void Main(string[] args)
    {
        var somestring = "asdf aaa Asdf";
        Console.WriteLine(UppercaseName(somestring));
        Console.ReadLine();
    }

    static string UppercaseName(string fullName)
    {
        var split = fullName.Split(' ');
        var returnedName = "";

        foreach (var name in split)
        {
            if (name.Length == 0)
                continue;

            if (listOfPrepositions.Where(p => p.Equals(name)).Count() > 0)
            {
                returnedName += name + " ";
                continue; // skip if it's a preposition
            }

            // Set the first character in the string to be uppercase
            returnedName += char.ToUpper(name[0]) + name.Substring(1) + " ";

        }
        returnedName.TrimEnd(' ');
        return returnedName;
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top