我有一个字符串,其中包含大小写混合的单词。
例如:string myData = "一个简单字符串";
我需要将每个单词的第一个字符(由空格分隔)转换为大写。所以我想要的结果为:字符串myData ="一个简单的字符串";
有什么简单的方法吗?我不想分割字符串并进行转换(这将是我最后的手段)。另外,它保证字符串是英文的。
我有一个字符串,其中包含大小写混合的单词。
例如:string myData = "一个简单字符串";
我需要将每个单词的第一个字符(由空格分隔)转换为大写。所以我想要的结果为:字符串myData ="一个简单的字符串";
有什么简单的方法吗?我不想分割字符串并进行转换(这将是我最后的手段)。另外,它保证字符串是英文的。
当前回答
MSDN: TextInfo。ToTitleCase
确保你包括:使用系统。全球化
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
其他回答
public static string PropCase(string strText)
{
return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower());
}
这是另一种变化。基于这里的几个技巧,我将其简化为以下扩展方法,它非常适合我的目的:
public static string ToTitleCase(this string s) =>
CultureInfo.InvariantCulture.TextInfo.ToTitleCase(s.ToLower());
MSDN: TextInfo。ToTitleCase
确保你包括:使用系统。全球化
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
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;
}
即使是驼色大小写也能正常工作:'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();
}
}