2010-01-05 10 views

Respuesta

37

There is a function that capitalises the first letters of words, aunque debería ver la sección de observaciones, ya que tiene algunas limitaciones que pueden hacer que no sea adecuada para sus necesidades.

+2

Pero no adecuadamente ejemplos de casos apropiados, tales como "o'riley" a "O'Riley", en lugar de producir "O'riley". – midspace

+6

@midspace - Como dije, sí hay una función, pero debería leer la sección de comentarios. Este tipo de caso de borde se llama explícitamente por ahí. –

+6

@midspace Quizás esto sea exagerado, pero decidí hacer mi propia versión con 'Regex.Replace (input.ToLower(), @" \ b [az] ", m => m.Value.ToUpper())' – Michael

64
String s = "yOu caN Use thIs" 

s = System.Threading.Thread.CurrentThread 
      .CurrentCulture.TextInfo.ToTitleCase(s.ToLower()); 

La principal limitación que puedo ver con esto es que no es "verdadero" caso de título. es decir, en la frase "WaR y peaCe", la parte "y" debe estar en minúsculas en inglés. Sin embargo, este método lo capitalizaría.

+0

Repetición de la respuesta – SteveC

+23

¿Un voto a favor para publicar la respuesta unos momentos después del texto original? Todavía estaba escribiendo mi respuesta cuando se publicó la respuesta aceptada. !! –

+13

Upvote: en realidad proporcionó la respuesta, mientras que la respuesta aceptada es solo un enlace. ¡Muy apreciado! –

10

puede simplemente añadir algunos métodos de extensión al tipo Sting:

public static class StringExtension 
{ 
    /// <summary> 
    /// Use the current thread's culture info for conversion 
    /// </summary> 
    public static string ToTitleCase(this string str) 
    { 
     var cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; 
     return cultureInfo.TextInfo.ToTitleCase(str.ToLower()); 
    } 

    /// <summary> 
    /// Overload which uses the culture info with the specified name 
    /// </summary> 
    public static string ToTitleCase(this string str, string cultureInfoName) 
    { 
     var cultureInfo = new CultureInfo(cultureInfoName); 
     return cultureInfo.TextInfo.ToTitleCase(str.ToLower()); 
    } 

    /// <summary> 
    /// Overload which uses the specified culture info 
    /// </summary> 
    public static string ToTitleCase(this string str, CultureInfo cultureInfo) 
    { 
     return cultureInfo.TextInfo.ToTitleCase(str.ToLower()); 
    } 
} 
1

Esto debería funcionar.

public static string ToTitleCase(this string strX) 
{ 
    string[] aryWords = strX.Trim().Split(' '); 

    List<string> lstLetters = new List<string>(); 
    List<string> lstWords = new List<string>(); 

    foreach (string strWord in aryWords) 
    { 
     int iLCount = 0; 
     foreach (char chrLetter in strWord.Trim()) 
     { 
      if (iLCount == 0) 
      { 
       lstLetters.Add(chrLetter.ToString().ToUpper()); 
      } 
      else 
      { 
       lstLetters.Add(chrLetter.ToString().ToLower()); 
      } 
      iLCount++; 
     } 
     lstWords.Add(string.Join("", lstLetters)); 
     lstLetters.Clear(); 
    } 

    string strNewString = string.Join(" ", lstWords); 

    return strNewString; 
} 
8

Esto funciona

public static string ConvertTo_ProperCase(string text) 
{ 
    TextInfo myTI = new CultureInfo("en-US", false).TextInfo; 
    return myTI.ToTitleCase(text.ToLower()); 
}  
+0

realmente usando esto gracias .. – kplshrm7

+0

¡Perfecto !. Esto debe marcarse como Respuesta. – Armaan

Cuestiones relacionadas