将string转换为标题大小写

我有一个string,其中包含大小写字母的混合,例如“一个简单的string”。 我想要做的是将每个单词的第一个字符(我可以假定单词用空格分隔)转换为大写。 所以我想要的结果是“一个简单的string”。 有没有简单的方法来做到这一点? 我不想分割string,并进行转换(这将是我最后的手段)。 另外,保证string是英文的。

MSDN: TextInfo.ToTitleCase

string title = "war and peace"; TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; title = textInfo.ToTitleCase(title); //War And Peace 

尝试这个:

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

正如已经指出的,使用TextInfo.ToTitleCase可能不会给你你想要的确切结果。 如果你需要更多的控制输出,你可以做这样的事情:

 IEnumerable<char> CharsToTitleCase(string 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; } } 

然后像这样使用它:

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

又一个变化。 基于这里的几个技巧,我已经减less到这个扩展方法,这对我的目的很好:

 public static string ToTitleCase(this string s) { return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower()); } 

就我个人而言,我尝试了TextInfo.ToTitleCase方法,但是,我不明白为什么在所有字符都是高位字符时它不起作用。

虽然我喜欢Winston Smith提供的util函数,但是让我提供我目前使用的函数:

 public static String TitleCaseString(String s) { if (s == null) return s; String[] 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].Substring(1).ToLower(); } words[i] = firstChar + rest; } return String.Join(" ", words); } 

玩一些testingstring:

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

输出

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

最近我find了更好的解决scheme。

如果你的文本包含大写的每一个字母,那么TextInfo将不会把它转换成适当的情况,那么,我们可以通过在里面使用小写函数来解决这个问题。

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

而且,现在这将转换所有进入Propercase。

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

这是对这个问题的解决scheme…

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

如果有人对Compact Framework的解决scheme感兴趣:

 return String.Join(" ", thestring.Split(' ').Select(i => i.Substring(0, 1).ToUpper() + i.Substring(1).ToLower()).ToArray()); 

首先使用ToLower() ,比结果中的CultureInfo.CurrentCulture.TextInfo.ToTitleCase获得正确的输出。

  //--------------------------------------------------------------- // Get title case of a string (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 string ToTitleCase(string str) { return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower()); } 

我需要一种处理所有大写字母的方法,而且我喜欢Ricky AH的解决scheme,但是我更进一步实施它作为扩展方法。 这避免了必须创build你的字符数组的步骤,然后每次都显式调用ToArray – 所以你可以在string上调用它,就像这样:

用法:

 string newString = oldString.ToProper(); 

码:

 public static class StringExtensions { public static string ToProper(this string s) { return new string(s.CharsToTitleCase().ToArray()); } public static IEnumerable<char> CharsToTitleCase(this string 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; } } } 

通过尝试自己的代码更好理解…

阅读更多

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

1)将string转换为大写

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

2)将string转换为小写

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

3)将一个string转换为TitleCase

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

这是一个字符一个字符的实现。 应该与“(一二三)”

 public static string ToInitcap(this string str) { if (string.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); } 
  String TitleCaseString(String s) { if (s == null || s.Length == 0) return s; string[] 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); } 

尝试这个:

 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; } } 

在TextBox的TextChanged事件中调用此方法。

我使用了上面的参考和完整的解决scheme是:

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

//需要结果如“Infoa2z意味着所有信息”
//我们还需要将string转换为小写,否则不能正常工作。

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

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

在检查空或空string值以消除错误之后,可以使用这个简单的方法直接将文本或string更改为正确:

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

这是我使用,它适用于大多数情况下,除非用户决定通过按shift键或大写locking来覆盖它。 就像在Android和iOS键盘上一样。

 Private Class ProperCaseHandler Private Const wordbreak As String = " ,.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.ToString.ToUpper() e.Handled = False Else Dim lastChar As String = txtProperCase.Text.Substring(txtProperCase.SelectionStart - 1, 1) If wordbreak.Contains(lastChar) = True Then e.KeyChar = e.KeyChar.ToString.ToUpper() e.Handled = False End If End If End If Catch ex As Exception Exit Sub End Try End Sub End Class 

对于那些正在按键自动执行它的人,我在自定义的textboxcontrol上使用了vb.net中的以下代码 – 显然你也可以用普通的文本框来做 – 但是我喜欢为特定的控件添加循环代码的可能性通过自定义控件它适合OOP的概念。

 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 <Category("Behavior"), Description("When Enabled ensures for automatic proper casing of string"), Browsable(True)> Public Property ProperCasing As Boolean Get Return _ProperCasing End Get Set(value As Boolean) _ProperCasing = value End Set End Property End Class 

我知道这是一个古老的问题,但我正在为C寻找相同的东西,我想通了,所以我想我会张贴,如果别人正在寻找一种方式在C:

 char proper(char string[]){ 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; }