TextInfo.ToTitleCase(String) Método

Definición

Convierte la cadena especificada a mayúscula inicial (excepto las palabras que están totalmente en mayúsculas, que se consideran acrónimos).

public:
 System::String ^ ToTitleCase(System::String ^ str);
public string ToTitleCase (string str);
member this.ToTitleCase : string -> string
Public Function ToTitleCase (str As String) As String

Parámetros

str
String

Cadena que se va a convertir en mayúscula inicial.

Devoluciones

String

Cadena especificada convertida en mayúscula inicial.

Excepciones

str es null.

Ejemplos

En el ejemplo siguiente se cambia el uso de mayúsculas y minúsculas de una cadena en función de la referencia cultural en inglés (Estados Unidos), con el nombre de referencia cultural en-US.

using namespace System;
using namespace System::Globalization;
int main()
{
   
   // Defines the String* with mixed casing.
   String^ myString = "wAr aNd pEaCe";
   
   // Creates a TextInfo based on the S"en-US" culture.
   CultureInfo^ MyCI = gcnew CultureInfo( "en-US",false );
   TextInfo^ myTI = MyCI->TextInfo;
   
   // Changes a String* to lowercase.
   Console::WriteLine( "\"{0}\" to lowercase: {1}", myString, myTI->ToLower( myString ) );
   
   // Changes a String* to uppercase.
   Console::WriteLine( "\"{0}\" to uppercase: {1}", myString, myTI->ToUpper( myString ) );
   
   // Changes a String* to titlecase.
   Console::WriteLine( "\"{0}\" to titlecase: {1}", myString, myTI->ToTitleCase( myString ) );
}

/*
This code produces the following output.

S"wAr aNd pEaCe" to lowercase: war and peace
S"wAr aNd pEaCe" to uppercase: WAR AND PEACE
S"wAr aNd pEaCe" to titlecase: War And Peace

*/
using System;
using System.Globalization;

public class SamplesTextInfo  {

   public static void Main()  {

      // Defines the string with mixed casing.
      string myString = "wAr aNd pEaCe";

      // Creates a TextInfo based on the "en-US" culture.
      TextInfo myTI = new CultureInfo("en-US",false).TextInfo;

      // Changes a string to lowercase.
      Console.WriteLine( "\"{0}\" to lowercase: {1}", myString, myTI.ToLower( myString ) );

      // Changes a string to uppercase.
      Console.WriteLine( "\"{0}\" to uppercase: {1}", myString, myTI.ToUpper( myString ) );

      // Changes a string to titlecase.
      Console.WriteLine( "\"{0}\" to titlecase: {1}", myString, myTI.ToTitleCase( myString ) );
   }
}

/*
This code produces the following output.

"wAr aNd pEaCe" to lowercase: war and peace
"wAr aNd pEaCe" to uppercase: WAR AND PEACE
"wAr aNd pEaCe" to titlecase: War And Peace

*/
Imports System.Globalization

Public Class SamplesTextInfo

   Public Shared Sub Main()

      ' Defines the string with mixed casing.
      Dim myString As String = "wAr aNd pEaCe"

      ' Creates a TextInfo based on the "en-US" culture.
      Dim myTI As TextInfo = New CultureInfo("en-US", False).TextInfo

      ' Changes a string to lowercase.
      Console.WriteLine("""{0}"" to lowercase: {1}", myString, myTI.ToLower(myString))

      ' Changes a string to uppercase.
      Console.WriteLine("""{0}"" to uppercase: {1}", myString, myTI.ToUpper(myString))

      ' Changes a string to titlecase.
      Console.WriteLine("""{0}"" to titlecase: {1}", myString, myTI.ToTitleCase(myString))

   End Sub

End Class


'This code produces the following output.
'
'"wAr aNd pEaCe" to lowercase: war and peace
'"wAr aNd pEaCe" to uppercase: WAR AND PEACE
'"wAr aNd pEaCe" to titlecase: War And Peace

En el ejemplo siguiente, se pasa cada cadena de una matriz al método ToTitleCase. Las cadenas incluyen cadenas de título correctas así como acrónimos. Las cadenas se convierten en mayúsculas y minúsculas mediante las convenciones de la referencia cultural en-US.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] values = { "a tale of two cities", "gROWL to the rescue",
                          "inside the US government", "sports and MLB baseball",
                          "The Return of Sherlock Holmes", "UNICEF and children"};

      TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
      foreach (var value in values)
         Console.WriteLine("{0} --> {1}", value, ti.ToTitleCase(value));
   }
}
// The example displays the following output:
//    a tale of two cities --> A Tale Of Two Cities
//    gROWL to the rescue --> Growl To The Rescue
//    inside the US government --> Inside The US Government
//    sports and MLB baseball --> Sports And MLB Baseball
//    The Return of Sherlock Holmes --> The Return Of Sherlock Holmes
//    UNICEF and children --> UNICEF And Children
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim values() As String = { "a tale of two cities", "gROWL to the rescue",
                                 "inside the US government", "sports and MLB baseball",
                                 "The Return of Sherlock Holmes", "UNICEF and children"}
                                 
      Dim ti As TextInfo = CultureInfo.CurrentCulture.TextInfo
      For Each value In values
         Console.WriteLine("{0} --> {1}", value, ti.ToTitleCase(value))
      Next
   End Sub
End Module
' The example displays the following output:
'    a tale of two cities --> A Tale Of Two Cities
'    gROWL to the rescue --> Growl To The Rescue
'    inside the US government --> Inside The US Government
'    sports and MLB baseball --> Sports And MLB Baseball
'    The Return of Sherlock Holmes --> The Return Of Sherlock Holmes
'    UNICEF and children --> UNICEF And Children

Comentarios

Por lo general, el uso de mayúsculas y minúsculas convierte el primer carácter de una palabra en mayúsculas y el resto de los caracteres en minúsculas. Sin embargo, este método no proporciona actualmente mayúsculas y minúsculas adecuadas para convertir una palabra que esté completamente en mayúsculas, como un acrónimo. En la tabla siguiente se muestra la forma en que el método representa varias cadenas.

Entrada Idioma Resultado esperado Resultado real
war and war and war Inglés Guerra y guerra Guerra y guerra
Per anhalter durch die Galaxis Alemán Per Anhalter durch die Galaxis Per Anhalter Durch Die Galaxis
lesfragés d'ylgq Francés LesFragés d'Ylgq LesFragés D'ylgq

Como se muestra anteriormente, el método proporciona un comportamiento arbitrario de mayúsculas y minúsculas ToTitleCase que no es necesariamente lingüísticamente correcto. Una solución lingüísticamente correcta requeriría reglas adicionales y el algoritmo actual es algo más sencillo y rápido. Nos reservamos el derecho de hacer que esta API sea más lenta en el futuro.

La implementación actual del método ToTitleCase produce una cadena de salida que tiene la misma longitud que la cadena de entrada. Sin embargo, este comportamiento no está garantizado y podría cambiar en una implementación futura.

Se aplica a

Consulte también