What is the best way to convert a string to Capitalize? [duplicate]

0

I have a string which I need to convert its value to capitalize . Example:

string cadena = "HOLA MUNDO";

I need to return the value like this - > Hello World

What would be the best way to achieve this?

    
asked by vcasas 15.05.2018 в 22:58
source

2 answers

1

You can solve it with two regular expressions:

var cadena = "HOLA MUNDO";
var result = Regex.Replace(cadena.ToLower(), @"\b(\w)", m => m.Value.ToUpper());
result = Regex.Replace(result, @"(\s(of|in|by|and)|\'[st])\b", m => m.Value.ToLower(), RegexOptions.IgnoreCase);

Taken from this Stack Overflow post in English: link

    
answered by 15.05.2018 / 23:07
source
7

You can also do it this way:

TextInfo.ToTitleCase() capitalizes the first character in each symbol of a string. If it is not necessary to keep Acronym Uppercasing , then you must include ToLower() .

string cadena = "HOLA MUNDO";
cadena = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(cadena.ToLower());
  

Result: "Hello World"

If CurrentCulture is not available, use:

string cadena = "HOLA MUNDO";
cadena = new System.Globalization.CultureInfo("es-ES", false).TextInfo.ToTitleCase(cadena.ToLower());
  

See the MSDN link for a detailed description.

Long Form :

You can use a function like this:

public static string PrimeraLetraMayuscula(string cadena)
{
    switch (cadena)
    {
        case null: throw new ArgumentNullException(nameof(cadena));
        case "": throw new ArgumentException($"{nameof(cadena)} no puede estar vacío", nameof(cadena));
        default: return cadena.First().ToString().ToUpper() + cadena.Substring(1);
    }
}
  

This function is found in this answer SO: link

    
answered by 15.05.2018 в 23:34