Answers:
MSDN:TextInfo.ToTitleCase
确保您包括: using System.Globalization
string 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
Actual result: "War And Peace"
。
text = Regex.Replace(text, @"(?<!\S)\p{Ll}", m => m.Value.ToUpper());
,但这远非完美。例如,它仍然不处理引号或括号"(one two three)"
--> "(one Two Three)"
。在弄清楚这些情况后您可能想问一个新问题。
尝试这个:
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() );
另一个变化。根据这里的几个技巧,我将其简化为此扩展方法,该方法非常适合我的目的:
public static string ToTitleCase(this string s) =>
CultureInfo.InvariantCulture.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);
}
使用一些测试字符串:
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|
||
| |
||
ToLower()
,您希望自己完成所有工作,并在每个单独的字符上调用相同的函数,而不是调用整个字符串?这不仅是一个丑陋的解决方案,而且它的收益为零,甚至比内置功能花费的时间更长。
rest = words[i].Substring(1).ToLower();
public static string PropCase(string strText)
{
return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower());
}
如果有人对Compact Framework解决方案感兴趣:
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)
// i.e: 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的解决方案,但是我将其进一步扩展为将其实现为扩展方法。这避免了必须创建字符数组然后每次都在其上显式调用ToArray的步骤-因此您可以仅在字符串上调用它,如下所示:
用法:
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 lower = "converted from lowercase";
Console.WriteLine(lower.ToUpper());
2)将字符串转换为小写
string upper = "CONVERTED FROM UPPERCASE";
Console.WriteLine(upper.ToLower());
3)将字符串转换为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);
}
在检查了空或空字符串值以消除错误之后,可以使用此简单方法直接将文本或字符串更改为适当的值:
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;
}
尝试这个:
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事件中调用此方法。
我使用了以上参考,完整的解决方案是:
Use Namespace System.Globalization;
string str="INFOA2Z means all information";
//需要类似“ Infoa2z意味着所有信息”的结果
//我们还需要将字符串转换为小写,否则它将无法正常工作。
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#
这就是我使用的方法,它适用于大多数情况,除非用户决定通过按Shift或Caps Lock来覆盖它。就像在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中使用以下代码进行的-您显然也可以使用普通的textbox进行操作-但我喜欢为特定控件添加重复代码的可能性通过自定义控件,它适合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
即使在驼峰式情况下也可以正常工作:“ YourPage中的someText”
public static class StringExtensions
{
/// <summary>
/// Title case example: 'Some Text In Your Page'.
/// </summary>
/// <param name="text">Support camel and title cases combinations: 'someText in YourPage'</param>
public static string ToTitleCase(this string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
var result = string.Empty;
var splitedBySpace = text.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries);
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();
}
}
作为扩展方法:
/// <summary>
// Returns a copy of this string converted to `Title Case`.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The `Title Case` equivalent of the current string.</returns>
public static string ToTitleCase(this string value)
{
string result = string.Empty;
for (int i = 0; i < value.Length; i++)
{
char p = i == 0 ? char.MinValue : value[i - 1];
char c = value[i];
result += char.IsLetter(c) && ((p is ' ') || p is char.MinValue) ? $"{char.ToUpper(c)}" : $"{char.ToLower(c)}";
}
return result;
}
用法:
"kebab is DELICIOU's ;d c...".ToTitleCase();
结果:
Kebab Is Deliciou's ;d C...
另一种参考Microsoft.VisualBasic
(也处理大写字符串):
string properCase = Strings.StrConv(str, VbStrConv.ProperCase);
不使用TextInfo
:
public static string TitleCase(this string text, char seperator = ' ') =>
string.Join(seperator, text.Split(seperator).Select(word => new string(
word.Select((letter, i) => i == 0 ? char.ToUpper(letter) : char.ToLower(letter)).ToArray())));
它循环遍历每个单词中的每个字母,如果它是第一个字母,则将其转换为大写,否则将其转换为小写。
我知道这是一个老问题,但是我正在为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;
}