我有一个字符串,其中包含大小写字符混合的单词。
例如:string myData = "a Simple string";
我需要将每个单词的第一个字符(由空格分隔)转换为大写。所以我希望结果为:string myData ="A Simple String";
有什么简单的方法可以做到这一点?我不想拆分字符串并进行转换(这将是我最后的手段)。此外,保证字符串是英文的。
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
尝试这个:
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();
最近我找到了一个更好的解决方案。
如果您的文本包含大写的每个字母,则 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());
}
首先使用 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());
}
如果有人对 Compact Framework 的解决方案感兴趣:
return String.Join(" ", thestring.Split(' ').Select(i => i.Substring(0, 1).ToUpper() + i.Substring(1).ToLower()).ToArray());
这是该问题的解决方案...
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(txt);
我需要一种处理所有大写单词的方法,并且我喜欢 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());
我使用了上述参考资料,完整的解决方案是:
Use Namespace System.Globalization;
string str = "INFOA2Z means all information";
// 需要像“Infoa2z 表示所有信息”这样的结果 // 我们还需要将字符串转换为小写,否则无法正常工作。
TextInfo ProperCase = new CultureInfo("en-US", false).TextInfo;
str = ProperCase.ToTitleCase(str.toLower());
Change string to proper case in an ASP.NET Using C#
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);
}
不使用 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())));
它遍历每个单词中的每个字母,如果它是第一个字母则将其转换为大写,否则将其转换为小写。
在检查 null 或空字符串值以消除错误后,您可以使用此简单方法直接将文本或字符串更改为正确:
// Text to proper (Title Case):
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;
}
参考 Microsoft.VisualBasic
的替代方案(也处理大写字符串):
string properCase = Strings.StrConv(str, VbStrConv.ProperCase);
这是一个逐字符的实现。它应该与“(一二三)”一起使用:
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);
}
尝试这个:
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 事件中调用此方法。
这是我使用的,它适用于大多数情况,除非用户决定通过按下 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
作为扩展方法:
/// <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...
即使使用骆驼案,它也能正常工作:'someText in YourPage'
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();
}
}
对于那些希望在按键上自动执行此操作的人,我在自定义文本框控件上使用 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 中执行此操作的方法:
char proper(char string[])
{
int i = 0;
for(i=0; i<=25; i++)
{
string[i] = tolower(string[i]); // Converts all characters to lower case
if(string[i-1] == ' ') // If the character before is a space
{
string[i] = toupper(string[i]); // Converts characters after spaces to upper case
}
}
string[0] = toupper(string[0]); // Converts the first character to upper case
return 0;
}
Actual result: "War And Peace"
。text = Regex.Replace(text, @"(?<!\S)\p{Ll}", m => m.Value.ToUpper());
之类的东西,但它远非完美。例如,它仍然不处理引号或括号 -"(one two three)"
->"(one Two Three)"
。在明确您想对这些案例做什么之后,您可能想问一个新问题。