Conversion de chaîne en casse

J’ai une chaîne qui contient des mots dans un mélange de majuscules et de minuscules.

Par exemple: ssortingng myData = "a Simple ssortingng";

Je dois convertir le premier caractère de chaque mot (séparé par des espaces) en majuscules. Je veux donc le résultat comme ssortingng myData ="A Simple Ssortingng"; : ssortingng myData ="A Simple Ssortingng";

Y at-il un moyen facile de le faire? Je ne veux pas diviser la chaîne et faire la conversion (ce sera mon dernier recours). En outre, il est garanti que les chaînes sont en anglais.

MSDN: TextInfo.ToTitleCase

Assurez-vous que vous incluez: using System.Globalization

 ssortingng title = "war and peace"; TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; title = textInfo.ToTitleCase(title); Console.WriteLine(title) ; //War And Peace //When text is ALL UPPERCASE... title = "WAR AND PEACE" ; title = textInfo.ToTitleCase(title); Console.WriteLine(title) ; //WAR AND PEACE //You need to call ToLower to make it work title = textInfo.ToTitleCase(title.ToLower()); Console.WriteLine(title) ; //War And Peace 

Essaye ça:

 ssortingng myText = "a Simple ssortingng"; ssortingng asTitleCase = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo. ToTitleCase(myText.ToLower()); 

Comme cela a déjà été souligné, l’utilisation de TextInfo.ToTitleCase peut ne pas vous donner les résultats exacts souhaités. Si vous avez besoin de plus de contrôle sur la sortie, vous pouvez faire quelque chose comme ceci:

 IEnumerable CharsToTitleCase(ssortingng s) { bool newWord = true; foreach(char c in s) { if(newWord) { yield return Char.ToUpper(c); newWord = false; } else yield return Char.ToLower(c); if(c==' ') newWord = true; } } 

Et ensuite l’utiliser comme ça:

 var asTitleCase = new ssortingng( CharsToTitleCase(myText).ToArray() ); 

Encore une autre variante. Sur la base de plusieurs astuces, je l’ai réduite à cette méthode d’extension, qui convient parfaitement à mes besoins:

 public static ssortingng ToTitleCase(this ssortingng s) => CultureInfo.InvariantCulture.TextInfo.ToTitleCase(s.ToLower()); 

Personnellement, j’ai essayé la méthode TextInfo.ToTitleCase , mais je ne comprends pas pourquoi cela ne fonctionne pas lorsque tous les caractères sont en majuscule.

Bien que j’aime la fonction util fournie par Winston Smith , laissez-moi vous fournir la fonction que j’utilise actuellement:

 public static Ssortingng TitleCaseSsortingng(Ssortingng s) { if (s == null) return s; Ssortingng[] words = s.Split(' '); for (int i = 0; i < words.Length; i++) { if (words[i].Length == 0) continue; Char firstChar = Char.ToUpper(words[i][0]); String rest = ""; if (words[i].Length > 1) { rest = words[i].Subssortingng(1).ToLower(); } words[i] = firstChar + rest; } return Ssortingng.Join(" ", words); } 

Jouer avec des cordes de tests :

 Ssortingng ts1 = "Converting ssortingng to title case in C#"; Ssortingng ts2 = "C"; Ssortingng ts3 = ""; Ssortingng ts4 = " "; Ssortingng ts5 = null; Console.Out.WriteLine(Ssortingng.Format("|{0}|", TitleCaseSsortingng(ts1))); Console.Out.WriteLine(Ssortingng.Format("|{0}|", TitleCaseSsortingng(ts2))); Console.Out.WriteLine(Ssortingng.Format("|{0}|", TitleCaseSsortingng(ts3))); Console.Out.WriteLine(Ssortingng.Format("|{0}|", TitleCaseSsortingng(ts4))); Console.Out.WriteLine(Ssortingng.Format("|{0}|", TitleCaseSsortingng(ts5))); 

Donner en sortie :

 |Converting Ssortingng To Title Case In C#| |C| || | | || 

Récemment, j’ai trouvé une meilleure solution.

Si votre texte contient chaque lettre en majuscule, TextInfo ne le convertira pas en casse. Nous pouvons résoudre ce problème en utilisant la fonction minuscule comme ceci:

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

Maintenant, cela convertira tout ce qui entre dans Propercase.

 public static ssortingng PropCase(ssortingng strText) { return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower()); } 

Si quelqu’un est intéressé par la solution Compact Framework:

 return Ssortingng.Join(" ", thessortingng.Split(' ').Select(i => i.Subssortingng(0, 1).ToUpper() + i.Subssortingng(1).ToLower()).ToArray()); 

Voici la solution à ce problème …

 CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; ssortingng txt = textInfo.ToTitleCase(txt); 

Utilisez ToLower() premier lieu, puis CultureInfo.CurrentCulture.TextInfo.ToTitleCase sur le résultat pour obtenir le résultat correct.

  //--------------------------------------------------------------- // Get title case of a ssortingng (every word with leading upper case, // the rest is lower case) // ie: ABCD EFG -> Abcd Efg, // john doe -> John Doe, // miXEd CaSING - > Mixed Casing //--------------------------------------------------------------- public static ssortingng ToTitleCase(ssortingng str) { return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower()); } 

J’avais besoin d’un moyen de traiter tous les mots en majuscules, et j’aimais la solution de Ricky AH, mais j’ai décidé de l’implémenter en tant que méthode d’extension. Cela évite de devoir créer votre tableau de caractères, puis d’appeler explicitement ToArray à chaque fois – vous pouvez donc simplement l’appeler sur la chaîne, comme ceci:

usage:

 ssortingng newSsortingng = oldSsortingng.ToProper(); 

code:

 public static class SsortingngExtensions { public static ssortingng ToProper(this ssortingng s) { return new ssortingng(s.CharsToTitleCase().ToArray()); } public static IEnumerable CharsToTitleCase(this ssortingng s) { bool newWord = true; foreach (char c in s) { if (newWord) { yield return Char.ToUpper(c); newWord = false; } else yield return Char.ToLower(c); if (c == ' ') newWord = true; } } } 

Il vaut mieux comprendre en essayant votre propre code …

Lire la suite

http://www.stupidcodes.com/2014/04/convert-ssortingng-to-uppercase-proper-case.html

1) Convertir une chaîne en majuscule

 ssortingng lower = "converted from lowercase"; Console.WriteLine(lower.ToUpper()); 

2) Convertir une chaîne en minuscules

 ssortingng upper = "CONVERTED FROM UPPERCASE"; Console.WriteLine(upper.ToLower()); 

3) Convertir une chaîne en TitleCase

  CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; ssortingng txt = textInfo.ToTitleCase(TextBox1.Text()); 

Voici une implémentation, caractère par caractère. Devrait travailler avec “(One Two Three)”

 public static ssortingng ToInitcap(this ssortingng str) { if (ssortingng.IsNullOrEmpty(str)) return str; char[] charArray = new char[str.Length]; bool newWord = true; for (int i = 0; i < str.Length; ++i) { Char currentChar = str[i]; if (Char.IsLetter(currentChar)) { if (newWord) { newWord = false; currentChar = Char.ToUpper(currentChar); } else { currentChar = Char.ToLower(currentChar); } } else if (Char.IsWhiteSpace(currentChar)) { newWord = true; } charArray[i] = currentChar; } return new string(charArray); } 
 Ssortingng TitleCaseSsortingng(Ssortingng s) { if (s == null || s.Length == 0) return s; ssortingng[] splits = s.Split(' '); for (int i = 0; i < splits.Length; i++) { switch (splits[i].Length) { case 1: break; default: splits[i] = Char.ToUpper(splits[i][0]) + splits[i].Substring(1); break; } } return String.Join(" ", splits); } 

Essaye ça:

 using System.Globalization; using System.Threading; public void ToTitleCase(TextBox TextBoxName) { int TextLength = TextBoxName.Text.Length; if (TextLength == 1) { CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text); TextBoxName.SelectionStart = 1; } else if (TextLength > 1 && TextBoxName.SelectionStart < TextLength) { int x = TextBoxName.SelectionStart; CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text); TextBoxName.SelectionStart = x; } else if (TextLength > 1 && TextBoxName.SelectionStart >= TextLength) { CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text); TextBoxName.SelectionStart = TextLength; } } 

Appelez cette méthode dans l’événement TextChanged de la zone de texte.

J’ai utilisé les références ci-dessus et la solution complète est: –

 Use Namespace System.Globalization; ssortingng str="INFOA2Z means all information"; 

// Besoin d’un résultat comme “Infoa2z signifie toutes les informations”
// Nous devons également convertir la chaîne en minuscule, sinon elle ne fonctionne pas correctement.

 TextInfo ProperCase= new CultureInfo("en-US", false).TextInfo; str= ProperCase.ToTitleCase(str.toLower()); 

http://www.infoa2z.com/asp.net/change-ssortingng-to-proper-case-in-an-asp.net-using-c#

C’est ce que j’utilise et cela fonctionne dans la plupart des cas, à moins que l’utilisateur ne décide de le remplacer en appuyant sur Maj ou sur Maj. Comme sur les claviers Android et iOS.

 Private Class ProperCaseHandler Private Const wordbreak As Ssortingng = " ,.1234567890;/\-()#$%^&*€!~+=@" Private txtProperCase As TextBox Sub New(txt As TextBox) txtProperCase = txt AddHandler txt.KeyPress, AddressOf txtTextKeyDownProperCase End Sub Private Sub txtTextKeyDownProperCase(ByVal sender As System.Object, ByVal e As Windows.Forms.KeyPressEventArgs) Try If Control.IsKeyLocked(Keys.CapsLock) Or Control.ModifierKeys = Keys.Shift Then Exit Sub Else If txtProperCase.TextLength = 0 Then e.KeyChar = e.KeyChar.ToSsortingng.ToUpper() e.Handled = False Else Dim lastChar As Ssortingng = txtProperCase.Text.Subssortingng(txtProperCase.SelectionStart - 1, 1) If wordbreak.Contains(lastChar) = True Then e.KeyChar = e.KeyChar.ToSsortingng.ToUpper() e.Handled = False End If End If End If Catch ex As Exception Exit Sub End Try End Sub End Class 

Pour ceux qui cherchent à le faire automatiquement en appuyant sur keypress, je l’ai fait avec le code suivant dans vb.net sur un contrôle textbox personnalisé – vous pouvez évidemment aussi le faire avec un textbox normal – mais j’aime la possibilité d’append du code récurrent pour des contrôles spécifiques via des contrôles personnalisés, il convient au concept de POO.

 Imports System.Windows.Forms Imports System.Drawing Imports System.ComponentModel Public Class MyTextBox Inherits System.Windows.Forms.TextBox Private LastKeyIsNotAlpha As Boolean = True Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs) If _ProperCasing Then Dim c As Char = e.KeyChar If Char.IsLetter(c) Then If LastKeyIsNotAlpha Then e.KeyChar = Char.ToUpper(c) LastKeyIsNotAlpha = False End If Else LastKeyIsNotAlpha = True End If End If MyBase.OnKeyPress(e) End Sub Private _ProperCasing As Boolean = False  Public Property ProperCasing As Boolean Get Return _ProperCasing End Get Set(value As Boolean) _ProperCasing = value End Set End Property End Class 

Vous pouvez modifier directement le texte ou la chaîne à l’aide de cette méthode simple, après avoir vérifié les valeurs de chaîne vide ou vide afin d’éliminer les erreurs:

 public ssortingng textToProper(ssortingng text) { ssortingng ProperText = ssortingng.Empty; if (!ssortingng.IsNullOrEmpty(text)) { ProperText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text); } else { ProperText = ssortingng.Empty; } return ProperText; } 

Fonctionne bien même avec un cas camel: ‘someText in YourPage’

 public static class SsortingngExtensions { ///  /// Title case example: 'Some Text In Your Page'. ///  /// Support camel and title cases combinations: 'someText in YourPage' public static ssortingng ToTitleCase(this ssortingng text) { if (ssortingng.IsNullOrEmpty(text)) { return text; } var result = ssortingng.Empty; var splitedBySpace = text.Split(new[]{ ' ' }, SsortingngSplitOptions.RemoveEmptyEnsortinges); foreach (var sequence in splitedBySpace) { // let's check the letters. Sequence can contain even 2 words in camel case for (var i = 0; i < sequence.Length; i++) { var letter = sequence[i].ToString(); // if the letter is Big or it was spaced so this is a start of another word if (letter == letter.ToUpper() || i == 0) { // add a space between words result += ' '; } result += i == 0 ? letter.ToUpper() : letter; } } return result.Trim(); } } 

Je sais que c’est une vieille question, mais je cherchais la même chose pour C et je l’ai compris, alors j’ai pensé que je le posterais si quelqu’un d’autre cherchait un moyen dans C:

 char proper(char ssortingng[]){ int i = 0; for(i=0; i<=25; i++) { string[i] = tolower(string[i]); //converts all character to lower case if(string[i-1] == ' ') //if character before is a space { string[i] = toupper(string[i]); //converts characters after spaces to upper case } } string[0] = toupper(string[0]); //converts first character to upper case return 0; }