如何在 C# 中将名字和姓氏的第一个字母大写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/72831/
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-03 11:09:46  来源:igfitidea点击:

How do I capitalize first letter of first name and last name in C#?

提问by Mike Roosa

Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own?

有没有一种简单的方法可以将字符串的第一个字母大写并降低其余部分?是否有内置方法还是我需要自己制作?

采纳答案by ageektrapped

TextInfo.ToTitleCase()capitalizes the first character in each token of a string.
If there is no need to maintain Acronym Uppercasing, then you should include ToLower().

TextInfo.ToTitleCase()将字符串的每个标记中的第一个字符大写。
如果不需要维护 Acronym Uppercasing,则应包含ToLower().

string s = "JOHN DOE";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
// Produces "John Doe"

If CurrentCulture is unavailable, use:

如果 CurrentCulture 不可用,请使用:

string s = "JOHN DOE";
s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());

See the MSDN Linkfor a detailed description.

有关详细说明,请参阅MSDN 链接

回答by ckal

ToTitleCase() should work for you.

ToTitleCase() 应该适合你。

http://support.microsoft.com/kb/312890

http://support.microsoft.com/kb/312890

回答by Nathan Baulch

CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello world");

回答by rjzii

The most direct option is going to be to use the ToTitleCasefunction that is available in .NET which should take care of the name most of the time. As edgpointed out there are some names that it will not work for, but these are fairly rare so unless you are targeting a culture where such names are common it is not necessary something that you have to worry too much about.

最直接的选择是使用.NET 中可用的ToTitleCase函数,它应该在大多数情况下处理名称。正如edg指出的那样,有些名称不适用,但这些名称相当罕见,因此除非您针对的是此类名称很常见的文化,否则您不必太担心。

However if you are not working with a .NET langauge, then it depends on what the input looks like - if you have two separate fields for the first name and the last name then you can just capitalize the first letter lower the rest of it using substrings.

但是,如果您不使用 .NET 语言,则这取决于输入的外观 - 如果您有两个单独的名字和姓氏字段,那么您可以使用大写首字母将其其余部分降低子串。

firstName = firstName.Substring(0, 1).ToUpper() + firstName.Substring(1).ToLower();
lastName = lastName.Substring(0, 1).ToUpper() + lastName.Substring(1).ToLower();

However, if you are provided multiple names as part of the same string then you need to know how you are getting the information and split itaccordingly. So if you are getting a name like "John Doe" you an split the string based upon the space character. If it is in a format such as "Doe, John" you are going to need to split it based upon the comma. However, once you have it split apart you just apply the code shown previously.

但是,如果提供了多个名称作为同一字符串的一部分,那么您需要知道如何获取信息并相应地将其拆分。所以如果你得到一个像“John Doe”这样的名字,你可以根据空格字符拆分字符串。如果它采用“Doe, John”等格式,您将需要根据逗号将其拆分。但是,一旦将其拆分,您只需应用前面显示的代码即可。

回答by David C

CultureInfo.CurrentCulture.TextInfo.ToTitleCase ("my name");

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(“我的名字”);

returns ~ My Name

返回 ~ 我的名字

But the problem still exists with names like McFly as stated earlier.

但是问题仍然存在于前面提到的像 McFly 这样的名字上。

回答by FlySwat

If your using vS2k8, you can use an extension method to add it to the String class:

如果您使用的是 vS2k8,则可以使用扩展方法将其添加到 String 类中:

public static string FirstLetterToUpper(this String input)
{
    return input = input.Substring(0, 1).ToUpper() + 
       input.Substring(1, input.Length - 1);
}

回答by Michael Haren

Like edg indicated, you'll need a more complex algorithm to handle special names (this is probably why many places force everything to upper case).

就像 edg 指出的那样,您需要一个更复杂的算法来处理特殊名称(这可能是许多地方强制所有内容为大写的原因)。

Something like this untested c# should handle the simple case you requested:

像这样未经测试的 c# 应该处理您请求的简单情况:

public string SentenceCase(string input)
{
    return input(0, 1).ToUpper + input.Substring(1).ToLower;
}

回答by Tundey

The suggestions to use ToTitleCase won't work for strings that are all upper case. So you are gonna have to call ToUpper on the first char and ToLower on the remaining characters.

使用 ToTitleCase 的建议不适用于全部大写的字符串。所以你必须在第一个字符上调用 ToUpper ,在剩余的字符上调用 ToLower 。

回答by Jamie Ide

Mc and Mac are common surname prefixes throughout the US, and there are others. TextInfo.ToTitleCase doesn't handle those cases and shouldn't be used for this purpose. Here's how I'm doing it:

Mc 和 Mac 是美国常见的姓氏前缀,还有其他姓氏前缀。TextInfo.ToTitleCase 不处理这些情况,不应用于此目的。这是我的做法:

    public static string ToTitleCase(string str)
    {
        string result = str;
        if (!string.IsNullOrEmpty(str))
        {
            var words = str.Split(' ');
            for (int index = 0; index < words.Length; index++)
            {
                var s = words[index];
                if (s.Length > 0)
                {
                    words[index] = s[0].ToString().ToUpper() + s.Substring(1);
                }
            }
            result = string.Join(" ", words);
        }
        return result;
    }

回答by Eddie Velasquez

This class does the trick. You can add new prefixes to the _prefixesstatic string array.

这个类可以解决问题。您可以向_prefixes静态字符串数组添加新前缀。

public static class StringExtensions
{
        public static string ToProperCase( this string original )
        {
            if( String.IsNullOrEmpty( original ) )
                return original;

            string result = _properNameRx.Replace( original.ToLower( CultureInfo.CurrentCulture ), HandleWord );
            return result;
        }

        public static string WordToProperCase( this string word )
        {
            if( String.IsNullOrEmpty( word ) )
                return word;

            if( word.Length > 1 )
                return Char.ToUpper( word[0], CultureInfo.CurrentCulture ) + word.Substring( 1 );

            return word.ToUpper( CultureInfo.CurrentCulture );
        }

        private static readonly Regex _properNameRx = new Regex( @"\b(\w+)\b" );
        private static readonly string[] _prefixes = {
                                                         "mc"
                                                     };

        private static string HandleWord( Match m )
        {
            string word = m.Groups[1].Value;

            foreach( string prefix in _prefixes )
            {
                if( word.StartsWith( prefix, StringComparison.CurrentCultureIgnoreCase ) )
                    return prefix.WordToProperCase() + word.Substring( prefix.Length ).WordToProperCase();
            }

            return word.WordToProperCase();
        }
}