J'étais sur le point d'écrire ma propre extension C# pour convertir une chaîne de caractères en majuscules (c'est-à-dire en mettant la première lettre de chaque mot en majuscule), puis je me suis demandé s'il n'existait pas une fonction C# native pour faire cela... existe-t-il ?
- Conversion string en casse de titre en c# (5 réponses )
Réponses
Trop de publicités?String s = "yOu caN Use thIs"
s = System.Threading.Thread.CurrentThread
.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
La principale limite que je vois à cette méthode est qu'il ne s'agit pas d'une "vraie" casse de titre. Par exemple, dans la phrase "WaR aNd peaCe", la partie "and" devrait être en minuscule en anglais. Cette méthode le mettrait en majuscule.
Il existe une fonction qui met en majuscule les premières lettres des mots Vous devez cependant consulter la section des remarques, car il présente certaines limitations qui peuvent le rendre inadapté à vos besoins.
Vous pouvez simplement ajouter des méthodes d'extension au type 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());
}
}
Cela devrait fonctionner.
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;
}