将字符串转换为标题大小写

我有一个字符串,其中包含大小写混合的单词。

例如:string myData = "a Simple string";

我需要将每个单词的第一个字符(由空格分隔)转换为大写。因此,我希望结果为:string myData ="A Simple String";

有什么简单的方法吗?我不想分割字符串并进行转换(这将是我最后的手段)。另外,它保证字符串是英文的。

306279 次浏览

MSDN: __abc0

确保你包含: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() );

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

虽然我喜欢温斯顿·史密斯提供的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|
||
|   |
||

下面是这个问题的解决方案……

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

最近我找到了一个更好的解决方案。

如果你的文本包含所有大写字母,那么TextInfo将不会将其转换为正确的大小写。我们可以通过使用里面的小写函数来解决这个问题,就像这样:

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

现在这将把所有输入的内容转换为Propercase。

试试这个:< br >

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

.在TextBox的TextChanged事件中调用此方法
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());

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

阅读更多

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)转换String为TitleCase

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

我需要一种方法来处理所有大写单词,我喜欢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;
}
}


}

这是另一种变化。基于这里的几个技巧,我将其简化为以下扩展方法,它非常适合我的目的:

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

下面是一个逐字符的实现。它应该与&;(One Two Three)&;

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

我使用了上面的参考,一个完整的解决方案是:

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

//需要像“Infoa2z意味着所有信息”这样的结果 //我们也需要转换小写的字符串,否则它不能正常工作。< br > < br > < / p >

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


str = ProperCase.ToTitleCase(str.toLower());

在ASP中修改字符串为正确的大小写。/a> . NET

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

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

在检查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;
}

这就是我所使用的,它适用于大多数情况,除非用户决定通过按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

首先使用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());
}

对于那些想要自动按下键盘的人,我用下面的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

即使是驼色大小写也能正常工作:'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();
}
}

作为扩展方法:

/// <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())));

它循环每个单词中的每个字母,如果它是第一个字母,则将其转换为大写字母,否则将其转换为小写字母。