93

我可以编写自己的算法来做到这一点,但我觉得应该有相当于ruby​​ 在 C# 中的人性化。

我用谷歌搜索了它,但只找到了人性化日期的方法。

例子:

  • 一种将“Lorem Lipsum Et”变成“Lorem Lipsum et”的方法
  • 一种将“Lorem Lipsum et”变成“Lorem Lipsum Et”的方法
4

9 回答 9

152

正如@miguel's answer的评论中所讨论的,您可以使用TextInfo.ToTitleCase自 .NET 1.1 以来可用的。这是与您的示例相对应的一些代码:

string lipsum1 = "Lorem lipsum et";

// Creates a TextInfo based on the "en-US" culture.
TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;

// Changes a string to titlecase.
Console.WriteLine("\"{0}\" to titlecase: {1}", 
                  lipsum1, 
                  textInfo.ToTitleCase( lipsum1 )); 

// Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et

它将忽略所有大写的内容,例如“LOREM LIPSUM ET”,因为它会处理首字母缩略词在文本中的情况,以便“IEEE”(电气和电子工程师协会)不会变成“ieee”或“哎呀”。

但是,如果您只想将第一个字符大写,则可以执行此处的解决方案……或者您可以拆分字符串并将列表中的第一个字符大写:

string lipsum2 = "Lorem Lipsum Et";

string lipsum2lower = textInfo.ToLower(lipsum2);

string[] lipsum2split = lipsum2lower.Split(' ');

bool first = true;

foreach (string s in lipsum2split)
{
    if (first)
    {
        Console.Write("{0} ", textInfo.ToTitleCase(s));
        first = false;
    }
    else
    {
        Console.Write("{0} ", s);
    }
}

// Will output: Lorem lipsum et 
于 2009-05-27T07:08:56.777 回答
41

还有另一个优雅的解决方案:

ToTitleCase在项目的静态类中定义函数

using System.Globalization;

public static string ToTitleCase(this string title)
{
    return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title.ToLower()); 
}

然后在项目的任何地方像字符串扩展一样使用它:

"have a good day !".ToTitleCase() // "Have A Good Day !"
于 2017-07-11T12:27:17.073 回答
39

使用正则表达式看起来更干净:

string s = "the quick brown fox jumps over the lazy dog";
s = Regex.Replace(s, @"(^\w)|(\s\w)", m => m.Value.ToUpper());
于 2015-04-02T02:11:50.587 回答
2

如果您只想将第一个字符大写,只需将其粘贴在您自己的实用方法中即可:

return string.IsNullOrEmpty(str) 
    ? str
    : str[0].ToUpperInvariant() + str.Substring(1).ToLowerInvariant();

还有一个库方法可以将每个单词的第一个字符大写:

http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx

于 2009-05-26T22:34:18.133 回答
2

所有示例似乎都使其他字符首先降低,这不是我需要的。

customerName= CustomerName<-- 这就是我想要的

this is an example=This Is An Example

public static string ToUpperEveryWord(this string s)
{
    // Check for empty string.  
    if (string.IsNullOrEmpty(s))
    {
        return string.Empty;
    }

    var words = s.Split(' ');

    var t = "";
    foreach (var word in words)
    {
        t += char.ToUpper(word[0]) + word.Substring(1) + ' ';
    }
    return t.Trim();
}
于 2019-03-22T16:20:13.560 回答
1

CSS 技术没问题,但只会改变浏览器中字符串的呈现方式。更好的方法是在发送到浏览器之前使文本本身大写。

上述大多数实施都可以,但没有一个解决如果您有需要保留的混合大小写单词,或者如果您想使用真正的标题大小写会发生什么问题,例如:

“在哪里学习博士课程在美国”

或者

“国税局表格 UB40a”

同样使用 CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string) 会保留大写单词,如“sports and MLB棒球”中的“Sports And MLB Baseball”,但如果将整个字符串设为大写,则会导致问题。

所以我整理了一个简单的函数,通过将它们包含在 specialCases 和 lowerCases 字符串数组中,您可以保留大写和混合大小写的单词,并使小写的单词小写(如果它们不在短语的开头和结尾):

public static string TitleCase(string value) {
        string titleString = ""; // destination string, this will be returned by function
        if (!String.IsNullOrEmpty(value)) {
            string[] lowerCases = new string[12] { "of", "the", "in", "a", "an", "to", "and", "at", "from", "by", "on", "or"}; // list of lower case words that should only be capitalised at start and end of title
            string[] specialCases = new string[7] { "UK", "USA", "IRS", "UCLA", "PHd", "UB40a", "MSc" }; // list of words that need capitalisation preserved at any point in title
            string[] words = value.ToLower().Split(' ');
            bool wordAdded = false; // flag to confirm whether this word appears in special case list
            int counter = 1;
            foreach (string s in words) {

                // check if word appears in lower case list
                foreach (string lcWord in lowerCases) {
                    if (s.ToLower() == lcWord) {
                        // if lower case word is the first or last word of the title then it still needs capital so skip this bit.
                        if (counter == 0 || counter == words.Length) { break; };
                        titleString += lcWord;
                        wordAdded = true;
                        break;
                    }
                }

                // check if word appears in special case list
                foreach (string scWord in specialCases) {
                    if (s.ToUpper() == scWord.ToUpper()) {
                        titleString += scWord;
                        wordAdded = true;
                        break;
                    }
                }

                if (!wordAdded) { // word does not appear in special cases or lower cases, so capitalise first letter and add to destination string
                    titleString += char.ToUpper(s[0]) + s.Substring(1).ToLower();
                }
                wordAdded = false;

                if (counter < words.Length) {
                    titleString += " "; //dont forget to add spaces back in again!
                }
                counter++;
            }
        }
        return titleString;
    }

这只是一种快速简单的方法 - 如果您想花更多时间在上面,可能会有所改进。

如果您想保留“a”和“of”等较小单词的大写,那么只需将它们从特殊情况字符串数组中删除即可。不同的组织有不同的资本化规则。

您可以在此站点上看到此代码的示例:Egg Donation London - 此站点通过解析 url 例如“/services/uk-egg-bank/introduction”在页面顶部自动创建面包屑路径 - 然后每个路径中的文件夹名称将连字符替换为空格并将文件夹名称大写,因此 uk-egg-bank 变为 UK Egg Bank。(保留大写“UK”)

此代码的扩展可能是在共享文本文件、数据库表或 Web 服务中具有首字母缩写词和大写/小写单词的查找表,以便可以从一个地方维护混合大小写单词的列表并应用于许多不同的依赖于该功能的应用程序。

于 2014-10-24T10:27:33.090 回答
0

.NET 中没有用于正确语言大写的预构建解决方案。你要什么样的大写?您是否遵循《芝加哥风格手册》的惯例?AMA 还是 MLA?即使是简单的英文句子大写也有 1000 多个单词的特殊例外。我无法谈论 ruby​​ 的 humanize 做了什么,但我想它可能不遵循大写的语言规则,而是做一些更简单的事情。

在内部,我们遇到了同样的问题并且不得不编写相当多的代码来处理文章标题的正确(在我们的小世界中)大小写,甚至不考虑句子的大写。它确实变得“模糊”:)

这真的取决于你需要什么 - 你为什么要尝试将句子转换为正确的大写(以及在什么情况下)?

于 2009-05-26T22:48:57.090 回答
0

我使用自定义扩展方法实现了同样的目标。对于第一个子字符串的第一个字母,请使用方法yourString.ToFirstLetterUpper()。对于不包括冠词和一些命题的每个子串的首字母,使用 方法yourString.ToAllFirstLetterInUpper()。下面是一个控制台程序:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("this is my string".ToAllFirstLetterInUpper());
            Console.WriteLine("uniVersity of lonDon".ToAllFirstLetterInUpper());
        }
    }

    public static class StringExtension
    {
        public static string ToAllFirstLetterInUpper(this string str)
        {
            var array = str.Split(" ");

            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] == "" || array[i] == " " || listOfArticles_Prepositions().Contains(array[i])) continue;
                array[i] = array[i].ToFirstLetterUpper();
            }
            return string.Join(" ", array);
        }

        private static string ToFirstLetterUpper(this string str)
        {
            return str?.First().ToString().ToUpper() + str?.Substring(1).ToLower();
        }

        private static string[] listOfArticles_Prepositions()
        {
            return new[]
            {
                "in","on","to","of","and","or","for","a","an","is"
            };
        }
    }

输出

This is My String
University of London
Process finished with exit code 0.
于 2020-01-26T07:26:22.217 回答
-1

据我所知,如果不编写(或抄袭)代码,就没有办法做到这一点。C# 网络(哈!)你的上、下和标题(你有什么)案例:

http://support.microsoft.com/kb/312890/EN-US/

于 2009-05-26T22:34:57.150 回答