Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用C#大写每个单词的第一个字符或整个字符串的第一个字符?_C#_String_Humanize - Fatal编程技术网

如何使用C#大写每个单词的第一个字符或整个字符串的第一个字符?

如何使用C#大写每个单词的第一个字符或整个字符串的第一个字符?,c#,string,humanize,C#,String,Humanize,我可以编写自己的算法来实现这一点,但我觉得应该有与C#中相同的算法 我在谷歌上搜索了一下,但只找到了使约会人性化的方法 示例: 一种将“Lorem Lipsum Et”转换为“Lorem Lipsum Et”的方法 一种将“Lorem lipsum et”转换为“Lorem lipsum et”的方法 如果您只想大写第一个字符,只需将其插入您自己的实用方法中即可: return string.IsNullOrEmpty(str) ? str : str[0].ToUpperI

我可以编写自己的算法来实现这一点,但我觉得应该有与C#中相同的算法

我在谷歌上搜索了一下,但只找到了使约会人性化的方法

示例:

  • 一种将“Lorem Lipsum Et”转换为“Lorem Lipsum Et”的方法
  • 一种将“Lorem lipsum et”转换为“Lorem lipsum et”的方法

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

return string.IsNullOrEmpty(str) 
    ? str
    : str[0].ToUpperInvariant() + str.Substring(1).ToLowerInvariant();
还有一种库方法可以将每个单词的第一个字符大写:


据我所知,如果不编写(或抄袭)代码,就没有办法做到这一点。C#nets(ha!)您可以使用上、下和标题(您拥有的)案例:


在.NET中,没有预先构建的适当语言大写的解决方案。你想要什么样的资本化?你在遵循芝加哥风格惯例手册吗?AMA还是MLA?即使是简单的英语句子大写也有1000个单词的特殊例外。我不知道ruby的“人性化”是怎么做的,但我想它可能不遵循大写的语言规则,而是做了更简单的事情

在内部,我们遇到了同样的问题,必须编写大量代码来处理文章标题的大小写,甚至不考虑句子的大小写。它确实变得“模糊”:


这实际上取决于您需要什么-为什么您要尝试将句子转换为适当的大写字母(以及在什么上下文中)?

如的评论中所述,您可以使用自.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”,因为它会处理文本中首字母缩写的情况(这样“不会变成”nambla“或”nambla”)

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

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 

CSS技术还可以,但只会更改浏览器中字符串的表示形式。更好的方法是在发送到浏览器之前将文本本身大写

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

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
“在美国哪里学习博士课程”

“IRS表格UB40a”

同时使用CultureInfo.CurrentCulture.TextInfo.ToTitleCase(字符串)保留大写单词,如中所示 “sports and MLB Basketball”变成“sports and MLB Basketball”,但如果整个字符串都放在大写,则会引起问题

因此,我编写了一个简单的函数,它允许您保留大写和大小写混合的单词,并通过将小词包含在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;
    }
公共静态字符串标题库(字符串值){
string titleString=“;//目标字符串,这将由函数返回
如果(!String.IsNullOrEmpty(值)){
string[]lowerCases=新字符串[12]{“of”,“the”,“in”,“a”,“an”,“to”,“and”,“at”,“from”,“by”,“on”,“or”};//仅应在标题开头和结尾大写的小写单词列表
string[]specialCases=新字符串[7]{“英国”、“美国”、“美国国税局”、“加州大学洛杉矶分校”、“博士”、“UB40a”、“MSc”};//需要在标题中任何位置保留大写的单词列表
string[]words=value.ToLower().Split(“”);
bool wordAdded=false;//用于确认此单词是否出现在特殊情况列表中的标志
int计数器=1;
foreach(单词中的字符串s){
//检查单词是否出现在小写列表中
foreach(小写字符串){
如果(s.ToLower()==lcWord){
//如果小写单词是标题的第一个或最后一个单词,那么它仍然需要大写,所以跳过这一位。
if(counter==0 | | counter==words.Length){break;};
标题字符串+=lcWord;
wordAdded=true;
打破
}
}
//检查word是否出现在特殊情况列表中
foreach(特殊情况下的字符串scWord){
如果(s.ToUpper()==scWord.ToUpper()){
标题字符串+=scWord;
wordAdded=true;
打破
}
}
如果(!wordAdded){//word没有出现在特殊情况下或小写情况下,则将第一个字母大写并添加到目标字符串中
titleString+=char.ToUpper(s[0])+s.Substring(1.ToLower();
}
wordAdded=false;
if(计数器
这只是一个快速而简单的方法——如果你想花更多的时间在上面的话,可能会有一些改进

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

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

<
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 !"
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();
}
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.