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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1206019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:53:28  来源:igfitidea点击:

Converting string to title case

c#string

提问by Naveen

I have a string which contains words in a mixture of upper and lower case characters.

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

For example: string myData = "a Simple string";

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

I need to convert the first character of each word (separated by spaces) into upper case. So I want the result as: string myData ="A Simple String";

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

Is there any easy way to do this? I don't want to split the string and do the conversion (that will be my last resort). Also, it is guaranteed that the strings are in English.

有什么简单的方法可以做到这一点吗?我不想拆分字符串并进行转换(这将是我的最后手段)。此外,保证字符串是英文的。

采纳答案by Kobi

MSDN : TextInfo.ToTitleCase

MSDN : TextInfo.ToTitleCase

Make sure that you include: using System.Globalization

确保您包括: 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

回答by Winston Smith

Try this:

尝试这个:

string myText = "a Simple string";

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

As has already been pointed out, using TextInfo.ToTitleCase might not give you the exact results you want. If you need more control over the output, you could do something like this:

正如已经指出的那样,使用 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;
    }
}

And then use it like so:

然后像这样使用它:

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

回答by Luis Quijada

Personally I tried the TextInfo.ToTitleCasemethod, but, I don′t understand why it doesn′t work when all chars are upper-cased.

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

Though I like the util function provided by Winston Smith, let me provide the function I'm currently using:

虽然我喜欢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);
}

Playing with some testsstrings:

玩一些测试字符串:

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

Giving output:

给出输出

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

回答by Jade

Here's the solution for that problem...

这是该问题的解决方案......

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

回答by Binod

Recently I found a better solution.

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

If your text contains every letter in uppercase, then TextInfowill not convert it to the proper case. We can fix that by using the lowercase function inside like this:

如果您的文本包含大写的每个字母,则TextInfo不会将其转换为正确的大小写。我们可以通过在里面使用小写函数来解决这个问题:

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

Now this will convert everything that comes in to Propercase.

现在这将把所有的东西都转换成 Propercase。

回答by krishna

Try this:

尝试这个:

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


Call this method in the TextChanged event of the TextBox.


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

回答by Rajesh

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

回答by Mibou

If someone is interested for the solution for Compact Framework :

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

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

回答by Sunil Acharya

Its better to understand by trying your own code...

通过尝试自己的代码来更好地理解...

Read more

阅读更多

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

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

1) Convert a String to Uppercase

1) 将字符串转换为大写

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

2) Convert a String to Lowercase

2) 将字符串转换为小写

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

3) Convert a String to TitleCase

3) 将字符串转换为 TitleCase

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

回答by Adam Diament

I needed a way to deal with all caps words, and I liked Ricky AH's solution, but I took it a step further to implement it as an extension method. This avoids the step of having to create your array of chars then call ToArray on it explicitly every time - so you can just call it on the string, like so:

我需要一种处理所有大写单词的方法,我喜欢 Ricky AH 的解决方案,但我更进一步将其实现为扩展方法。这避免了必须创建字符数组然后每次显式调用 ToArray 的步骤 - 所以你可以在字符串上调用它,如下所示:

usage:

用法:

string newString = oldString.ToProper();

code:

代码:

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

}