IT story

C #에서 성과 이름의 첫 글자는 어떻게 대문자로 사용합니까?

hot-time 2020. 6. 21. 19:24
반응형

C #에서 성과 이름의 첫 글자는 어떻게 대문자로 사용합니까?


문자열의 첫 글자를 대문자로 바꾸고 나머지를 낮추는 쉬운 방법이 있습니까? 내장 된 방법이 있습니까, 아니면 직접 만들어야합니까?


TextInfo.ToTitleCase()문자열의 각 토큰에서 첫 번째 문자를 대문자로 표시합니다.
약어를 유지할 필요가 없으면을 포함해야합니다 ToLower().

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

CurrentCulture를 사용할 수 없으면 다음을 사용하십시오.

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

자세한 설명 MSDN 링크참조하십시오 .


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

String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test);

위의 코드는 작동하지 않습니다 .....

따라서 아래 코드를 더 낮게 변환하여 함수를 적용하십시오.

String test = "HELLO HOW ARE YOU";
string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(test.ToLower());

CultureInfo.CurrentCulture.TextInfo.ToTitleCase처리 할 수없는 경우가 있습니다 (예 : 아포스트로피) '.

string input = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("o'reilly, m'grego, d'angelo");
// input = O'reilly, M'grego, D'angelo

정규식 도 사용할 수 있습니다 \b[a-zA-Z]단어 경계 후 단어의 시작 문자를 식별하기 위해 \b우리는 그것의 대문자 등가 힘 입어 경기를 교체 할 단지 필요가 Regex.Replace(string input,string pattern,MatchEvaluator evaluator)방법 :

string input = "o'reilly, m'grego, d'angelo";
input = Regex.Replace(input.ToLower(), @"\b[a-zA-Z]", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo

정규식이 필요한 경우 우리가 처리 할 경우, 예를 들어, 조정할 수 있습니다 MacDonaldMcFry정규식이 될 경우를 :(?<=\b(?:mc|mac)?)[a-zA-Z]

string input = "o'reilly, m'grego, d'angelo, macdonald's, mcfry";
input = Regex.Replace(input.ToLower(), @"(?<=\b(?:mc|mac)?)[a-zA-Z]", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo, MacDonald'S, McFry

더 많은 접두사를 처리해야하는 경우 그룹을 수정하기 (?:mc|mac)만하면됩니다 (예 du, de: 프랑스어 접두사 추가) (?:mc|mac|du|de).

마지막으로, 우리는이 정규 표현식MacDonald'S마지막 경우와 일치 한다는 것을 알 수 's있으므로 부정적인 표정으로 정규 표현식 에서 처리해야합니다 (?<!'s\b). 결국 우리는 :

string input = "o'reilly, m'grego, d'angelo, macdonald's, mcfry";
input = Regex.Replace(input.ToLower(), @"(?<=\b(?:mc|mac)?)[a-zA-Z](?<!'s\b)", m => m.Value.ToUpper());
// input = O'Reilly, M'Grego, D'Angelo, MacDonald's, McFry

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

ToTitleCase ()가 도움이 될 것입니다.

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


가장 직접적인 옵션은 .NET에서 사용 가능한 ToTitleCase 함수 를 사용 하는 것입니다. 대부분의 경우 이름을 처리해야합니다. edg가 지적한 바와 같이 , 효과가 없을만한 이름이 있지만, 그 이름은 매우 드물기 때문에 그러한 이름이 일반적인 문화를 타겟팅하지 않으면 너무 걱정할 필요가 없습니다.

그러나 .NET 언어로 작업하지 않는 경우 입력 모양에 따라 달라집니다. 이름과성에 대해 두 개의 별도 필드가있는 경우 첫 번째 문자를 대문자로 사용하여 나머지를 낮출 수 있습니다 부분 문자열.

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

그러나 동일한 문자열의 일부로 여러 이름이 제공되는 경우 정보를 얻는 방법을 알고 이를 적절히 분할해야합니다 . "John Doe"와 같은 이름을 얻으면 공백 문자를 기준으로 문자열을 분할합니다. "Doe, John"과 같은 형식 인 경우 쉼표를 기준으로 분할해야합니다. 그러나 일단 분할하면 이전에 표시된 코드 만 적용하면됩니다.


CultureInfo.CurrentCulture.TextInfo.ToTitleCase ( "내 이름");

~ 내 이름을 반환

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


I use my own method to get this fixed:

For example the phrase: "hello world. hello this is the stackoverflow world." will be "Hello World. Hello This Is The Stackoverflow World.". Regex \b (start of a word) \w (first charactor of the word) will do the trick.

/// <summary>
/// Makes each first letter of a word uppercase. The rest will be lowercase
/// </summary>
/// <param name="Phrase"></param>
/// <returns></returns>
public static string FormatWordsWithFirstCapital(string Phrase)
{
     MatchCollection Matches = Regex.Matches(Phrase, "\\b\\w");
     Phrase = Phrase.ToLower();
     foreach (Match Match in Matches)
         Phrase = Phrase.Remove(Match.Index, 1).Insert(Match.Index, Match.Value.ToUpper());

     return Phrase;
}

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.


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

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

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

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

To get round some of the issues/problems that have ben highlighted I would suggest converting the string to lower case first and then call the ToTitleCase method. You could then use IndexOf(" Mc") or IndexOf(" O\'") to determine special cases that need more specific attention.

inputString = inputString.ToLower();
inputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);
int indexOfMc = inputString.IndexOf(" Mc");
if(indexOfMc  > 0)
{
   inputString.Substring(0, indexOfMc + 3) + inputString[indexOfMc + 3].ToString().ToUpper() + inputString.Substring(indexOfMc + 4);
}

I like this way:

using System.Globalization;
...
TextInfo myTi = new CultureInfo("en-Us",false).TextInfo;
string raw = "THIS IS ALL CAPS";
string firstCapOnly = myTi.ToTitleCase(raw.ToLower());

Lifted from this MSDN article.


Hope this helps you.

String fName = "firstname";
String lName = "lastname";
String capitalizedFName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fName);
String capitalizedLName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lName);

 public static string ConvertToCaptilize(string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                string[] arrUserInput = input.Split(' ');


                // Initialize a string builder object for the output
                StringBuilder sbOutPut = new StringBuilder();


                // Loop thru each character in the string array
                foreach (string str in arrUserInput)
                {
                    if (!string.IsNullOrEmpty(str))
                    {
                        var charArray = str.ToCharArray();
                        int k = 0;
                        foreach (var cr in charArray)
                        {
                            char c;
                            c = k == 0 ? char.ToUpper(cr) : char.ToLower(cr);
                            sbOutPut.Append(c);
                            k++;
                        }


                    }
                    sbOutPut.Append(" ");
                }
                return sbOutPut.ToString();
            }
            return string.Empty;

        }

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

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

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

참고URL : https://stackoverflow.com/questions/72831/how-do-i-capitalize-first-letter-of-first-name-and-last-name-in-c

반응형