developer tip

모든 첫 글자를 대문자로 변환하고 각 단어에 대해 더 낮게 유지

optionbox 2020. 8. 8. 12:29
반응형

모든 첫 글자를 대문자로 변환하고 각 단어에 대해 더 낮게 유지


변환해야하는 텍스트 문자열 (대부분 약 5-6 단어)이 있습니다.

현재 텍스트는 다음과 같습니다.

THIS IS MY TEXT RIGHT NOW

다음으로 변환하고 싶습니다.

This Is My Text Right Now

문자열 컬렉션을 반복 할 수 있지만이 텍스트 수정을 수행하는 방법을 모르겠습니다.


string s = "THIS IS MY TEXT RIGHT NOW";

s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

Thread.CurrentThread ( System.Threading ) 보다 CultureInfo ( System.Globalization ) 에서 ToTitleCase 를 호출하는 것을 선호합니다.

string s = "THIS IS MY TEXT RIGHT NOW";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

하지만 jspcal 솔루션과 동일해야합니다.

편집하다

실제로 이러한 솔루션은 동일하지 않습니다 . CurrentThread--calls-> CultureInfo!


System.Threading.Thread.CurrentThread.CurrentCulture

string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

IL_0000:  ldstr       "THIS IS MY TEXT RIGHT NOW"
IL_0005:  stloc.0     // s
IL_0006:  call        System.Threading.Thread.get_CurrentThread
IL_000B:  callvirt    System.Threading.Thread.get_CurrentCulture
IL_0010:  callvirt    System.Globalization.CultureInfo.get_TextInfo
IL_0015:  ldloc.0     // s
IL_0016:  callvirt    System.String.ToLower
IL_001B:  callvirt    System.Globalization.TextInfo.ToTitleCase
IL_0020:  stloc.0     // s

System.Globalization.CultureInfo.CurrentCulture

string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

IL_0000:  ldstr       "THIS IS MY TEXT RIGHT NOW"
IL_0005:  stloc.0     // s
IL_0006:  call        System.Globalization.CultureInfo.get_CurrentCulture
IL_000B:  callvirt    System.Globalization.CultureInfo.get_TextInfo
IL_0010:  ldloc.0     // s
IL_0011:  callvirt    System.String.ToLower
IL_0016:  callvirt    System.Globalization.TextInfo.ToTitleCase
IL_001B:  stloc.0     // s

참조 :


There's a couple of ways to go about converting the first char of a string to upper case.

The first way is to create a method that simply caps the first char and appends the rest of the string using a substring:

public string UppercaseFirst(string s)
    {
        return char.ToUpper(s[0]) + s.Substring(1);
    }

The second way (which is slightly faster) is to split the string into a char array and then re-build the string:

public string UppercaseFirst(string s)
    {
        char[] a = s.ToCharArray();
        a[0] = char.ToUpper(a[0]);
        return new string(a);
    }

If you're using on a web page, you can also use CSS:

style="text-transform:capitalize;"


Untested but something like this should work:

var phrase = "THIS IS MY TEXT RIGHT NOW";
var rx = new System.Text.RegularExpressions.Regex(@"(?<=\w)\w");
var newString = rx.Replace(phrase,new MatchEvaluator(m=>m.Value.ToLowerInvariant()));

Essentially it says "preform a regex match on all occurrences of an alphanumeric character that follows another alphanumeric character and then replace it with a lowercase version of itself"


When building big tables speed is a concern so Jamie Dixon's second function is best, but it doesn't completely work as is...

It fails to take all of the letters to lowercase, and it only capitalizes the first letter of the string, not the first letter of each word in the string... the below option fixes both issues:

    public string UppercaseFirstEach(string s)
    {
        char[] a = s.ToLower().ToCharArray();

        for (int i = 0; i < a.Count(); i++ )
        {
            a[i] = i == 0 || a[i-1] == ' ' ? char.ToUpper(a[i]) : a[i];

        }

        return new string(a);
    }

Although at this point, whether this is still the fastest option is uncertain, the Regex solution provided by George Mauer might be faster... someone who cares enough should test it.


I don't know if the solution below is more or less efficient than jspcal's answer, but I'm pretty sure it requires less object creation than Jamie's and George's.

string s = "THIS IS MY TEXT RIGHT NOW";
StringBuilder sb = new StringBuilder(s.Length);
bool capitalize = true;
foreach (char c in s) {
    sb.Append(capitalize ? Char.ToUpper(c) : Char.ToLower(c));
    capitalize = !Char.IsLetter(c);
}
return sb.ToString();

In addition to first answer, remember to change string selectionstart index to the end of the word or you will get reverse order of letters in the string.

s.SelectionStart=s.Length;

Try this technique; It returns the desired result

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());

And don't forget to use System.Globalization.


One of the possible solution you might be interested in. Traversing an array of chars from right to left and vise versa in one loop.

public static string WordsToCapitalLetter(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentException("value");
        }

        int inputValueCharLength = value.Length;
        var valueAsCharArray = value.ToCharArray();

        int min = 0;
        int max = inputValueCharLength - 1;

        while (max > min)
        {
            char left = value[min];
            char previousLeft = (min == 0) ? left : value[min - 1];

            char right = value[max];
            char nextRight = (max == inputValueCharLength - 1) ? right : value[max - 1];

            if (char.IsLetter(left) && !char.IsUpper(left) && char.IsWhiteSpace(previousLeft))
            {
                valueAsCharArray[min] = char.ToUpper(left);
            }

            if (char.IsLetter(right) && !char.IsUpper(right) && char.IsWhiteSpace(nextRight))
            {
                valueAsCharArray[max] = char.ToUpper(right);
            }

            min++;
            max--;
        }

        return new string(valueAsCharArray);
    }

참고URL : https://stackoverflow.com/questions/1943273/convert-all-first-letter-to-upper-case-rest-lower-for-each-word

반응형