Programming

문자열의 첫 글자를 대문자로 만듭니다 (성능 극대화).

procodes 2020. 2. 21. 22:34
반응형

문자열의 첫 글자를 대문자로 만듭니다 (성능 극대화).


나는이 DetailsViewA를을 TextBox하고 내가 원하는 입력 데이터가 될 수 항상 저장 첫 글자 자본으로.

예:

"red" --> "Red"
"red house" --> " Red house"

최대 성능을 어떻게 달성 할 수 있습니까?


참고 :
답변과 답변 아래의 주석을 기반으로 많은 사람들은 이것이 문자열의 모든 단어를 대문자로 쓰는 것에 대해 묻는 것이라고 생각 합니다. 예를 들어 => Red House , 그렇지 않지만 그것이 원하는 경우TextInfoToTitleCase방법 을 사용하는 답변 중 하나를 찾으십시오 . (참고 : 이 질문에 대한 답변은 실제로 질문 한 내용에 맞지 않습니다 .) 주의 사항에
대해서는 TextInfo.ToTitleCase 문서참조하십시오 (모두 대문자 단어를 건드리지 마십시오. 두문자어로 간주됩니다. 예 : "McDonald"=> "Mcdonald"; 모든 문화 관련 미묘한 부분을 대문자로 처리한다는 보장은 없습니다.)


참고 :
질문은 모호한 처음 후에 문자가되어야하는지에 강제 하는 소문자 . 수락 된 답변은 첫 글자 만 변경해야 한다고 가정합니다 . 당신이 강제하려면 첫 번째를 제외하고 문자열의 모든 문자를 소문자로, 답변에 대한보기는 포함 ToLower하고 ToTitleCase을 포함하지 않는 .


C # 8로 업데이트

public static class StringExtensions
{
    public static string FirstCharToUpper(this string input) =>
        input switch
        {
            null => throw new ArgumentNullException(nameof(input)),
            "" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)),
            _ => input.First().ToString().ToUpper() + input.Substring(1)
        }
    }
}

C # 7

public static class StringExtensions
{
    public static string FirstCharToUpper(this string input)
    {
        switch (input)
        {
            case null: throw new ArgumentNullException(nameof(input));
            case "": throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input));
            default: return input.First().ToString().ToUpper() + input.Substring(1);
        }
    }
}

정말 오래된 답변

public static string FirstCharToUpper(string input)
{
    if (String.IsNullOrEmpty(input))
        throw new ArgumentException("ARGH!");
    return input.First().ToString().ToUpper() + String.Join("", input.Skip(1));
}

편집 :이 버전이 더 짧습니다. 빠른 솔루션을 위해 Equiso의 답변을 살펴보십시오.

public static string FirstCharToUpper(string input)
{
    if (String.IsNullOrEmpty(input))
        throw new ArgumentException("ARGH!");
    return input.First().ToString().ToUpper() + input.Substring(1);
}

편집 2 : 아마도 가장 빠른 솔루션은 Darren ( 아마도 벤치 마크가 있음) 일 것입니다. 그러나 string.IsNullOrEmpty(s)원래 요구 사항은 첫 글자가 존재할 것으로 예상되므로 대문자를 사용할 수 있기 때문에 예외를 던지는 유효성 검사를 변경합니다 . 이 코드는 일반 문자열에 적용되며 특히의 유효한 값에는 적용되지 않습니다 Textbox.


public string FirstLetterToUpper(string str)
{
    if (str == null)
        return null;

    if (str.Length > 1)
        return char.ToUpper(str[0]) + str.Substring(1);

    return str.ToUpper();
}

이전 답변 : 모든 첫 글자를 대문자로 만듭니다.

public string ToTitleCase(string str)
{
    return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}

올바른 방법은 문화를 사용하는 것입니다.

System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())

참고 : 이렇게하면 문자열 내에서 각 단어를 대문자로 표시합니다 (예 : "red house"-> "Red House"). 이 솔루션은 "old McDonald"-> "Old Mcdonald"와 같은 단어 내에서 대문자를 사용합니다.


http://www.dotnetperls.com/uppercase-first-letter 에서 가장 빠른 방법을 사용 하여 확장 방법으로 변환했습니다.

    /// <summary>
    /// Returns the input string with the first character converted to uppercase, or mutates any nulls passed into string.Empty
    /// </summary>
    public static string FirstLetterToUpperCaseOrConvertNullToEmptyString(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return string.Empty;

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

참고 : 사용하는 ToCharArray것이 대안보다 빠르다는 이유 char.ToUpper(s[0]) + s.Substring(1)하나의 문자열 만 할당되는 반면 Substring접근법은 하위 문자열에 문자열을 할당 한 다음 두 번째 문자열을 사용하여 최종 결과를 작성하기 때문입니다.


편집 : 다음은 CarlosMuñoz 의 초기 테스트와 함께이 접근법이 어떻게 보이는지에 대한 대답입니다 .

    /// <summary>
    /// Returns the input string with the first character converted to uppercase
    /// </summary>
    public static string FirstLetterToUpperCase(this string s)
    {
        if (string.IsNullOrEmpty(s))
            throw new ArgumentException("There is no first letter");

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

"ToTitleCase 메서드"를 사용할 수 있습니다

string s = new CultureInfo("en-US").TextInfo.ToTitleCase("red house");
//result : Red House

이 확장 방법은 모든 타이틀 케이스 문제를 해결합니다.

사용하기 쉬운

string str = "red house";
str.ToTitleCase();
//result : Red house

string str = "red house";
str.ToTitleCase(TitleCase.All);
//result : Red House

확장 방법

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace Test
{
    public static class StringHelper
    {
        private static CultureInfo ci = new CultureInfo("en-US");
        //Convert all first latter
        public static string ToTitleCase(this string str)
        {
            str = str.ToLower();
            var strArray = str.Split(' ');
            if (strArray.Length > 1)
            {
                strArray[0] = ci.TextInfo.ToTitleCase(strArray[0]);
                return string.Join(" ", strArray);
            }
            return ci.TextInfo.ToTitleCase(str);
        }
        public static string ToTitleCase(this string str, TitleCase tcase)
        {
            str = str.ToLower();
            switch (tcase)
            {
                case TitleCase.First:
                    var strArray = str.Split(' ');
                    if (strArray.Length > 1)
                    {
                        strArray[0] = ci.TextInfo.ToTitleCase(strArray[0]);
                        return string.Join(" ", strArray);
                    }
                    break;
                case TitleCase.All:
                    return ci.TextInfo.ToTitleCase(str);
                default:
                    break;
            }
            return ci.TextInfo.ToTitleCase(str);
        }
    }

    public enum TitleCase
    {
        First,
        All
    }
}

오류 검사와 함께 첫 글자 :

public string CapitalizeFirstLetter(string s)
{
    if (String.IsNullOrEmpty(s))
        return s;
    if (s.Length == 1)
        return s.ToUpper();
    return s.Remove(1).ToUpper() + s.Substring(1);
}

그리고 여기는 편리한 확장과 같습니다

public static string CapitalizeFirstLetter(this string s)
    {
    if (String.IsNullOrEmpty(s)) return s;
    if (s.Length == 1) return s.ToUpper();
    return s.Remove(1).ToUpper() + s.Substring(1);
    }

public static string ToInvarianTitleCase(this string self)
{
    if (string.IsNullOrWhiteSpace(self))
    {
        return self;
    }

    return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(self);
}

성능 / 메모리 사용이 문제인 경우,이 문자열은 원래 문자열과 동일한 크기의 StringBuilder 1 개와 새 String 1 개만 만듭니다.

public static string ToUpperFirst(this string str) {
  if( !string.IsNullOrEmpty( str ) ) {
    StringBuilder sb = new StringBuilder(str);
    sb[0] = char.ToUpper(sb[0]);

    return sb.ToString();

  } else return str;
}

이 시도:

static public string UpperCaseFirstCharacter(this string text) {
    return Regex.Replace(text, "^[a-z]", m => m.Value.ToUpper());
}

첫 글자 만 대문자로 표시하고 나머지 문자열이 중요하지 않은 경우 첫 번째 문자를 선택하고 대문자를 사용하여 원래 첫 번째 문자없이 나머지 문자열과 연결할 수 있습니다.

String word ="red house";
word = word[0].ToString().ToUpper() + word.Substring(1, word.length -1);
//result: word = "Red house"

첫 문자 ToString ()을 Char 배열로 읽고 있기 때문에 변환해야하며 Char 유형에는 ToUpper () 메소드가 없습니다.


가장 빠른 방법.

  private string Capitalize(string s){
        if (string.IsNullOrEmpty(s))
        {
            return string.Empty;
        }
        char[] a = s.ToCharArray();
        a[0] = char.ToUpper(a[0]);
        return new string(a);
}

테스트 결과 다음 결과 표시 (입력으로 10000000 기호가있는 문자열) : 테스트 결과


확장 방법으로 수행하는 방법은 다음과 같습니다.

static public string UpperCaseFirstCharacter(this string text)
{
    if (!string.IsNullOrEmpty(text))
    {
        return string.Format(
            "{0}{1}",
            text.Substring(0, 1).ToUpper(),
            text.Substring(1));
    }

    return text;
}

그런 다음 다음과 같이 호출 할 수 있습니다.

//yields "This is Brian's test.":
"this is Brian's test.".UpperCaseFirstCharacter(); 

여기에 몇 가지 단위 테스트가 있습니다.

[Test]
public void UpperCaseFirstCharacter_ZeroLength_ReturnsOriginal()
{
    string orig = "";
    string result = orig.UpperCaseFirstCharacter();

    Assert.AreEqual(orig, result);
}

[Test]
public void UpperCaseFirstCharacter_SingleCharacter_ReturnsCapital()
{
    string orig = "c";
    string result = orig.UpperCaseFirstCharacter();

    Assert.AreEqual("C", result);
}

[Test]
public void UpperCaseFirstCharacter_StandardInput_CapitalizeOnlyFirstLetter()
{
    string orig = "this is Brian's test.";
    string result = orig.UpperCaseFirstCharacter();

    Assert.AreEqual("This is Brian's test.", result);
}

나는 이것에 대해서도 연구하고 아이디어를 찾고 있었기 때문에 이것이 내가 찾은 해결책입니다. LINQ를 사용하며 첫 번째 문자가 아닌 경우에도 문자열의 첫 문자를 대문자로 표시 할 수 있습니다. 내가 만든 확장 방법은 다음과 같습니다.

public static string CaptalizeFirstLetter(this string data)
{
    var chars = data.ToCharArray();

    // Find the Index of the first letter
    var charac = data.First(char.IsLetter);
    var i = data.IndexOf(charac);

    // capitalize that letter
    chars[i] = char.ToUpper(chars[i]);

    return new string(chars);
}

나는 이것을 조금 최적화하거나 정리하는 방법이 있다고 확신합니다.


나는 http://www.dotnetperls.com/uppercase-first-letter 에서 뭔가를 발견했다 .

static string UppercaseFirst(string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
    return string.Empty;
}
// Return char and concat substring.
return char.ToUpper(s[0]) + s.Substring(1);
}

어쩌면 이것은 도움이됩니다!


단어의 시작 부분에 잘못된 자본이없는지도 확인하지만 그렇게 할 것입니다.

public string(string s)
{
System.Globalization.CultureInfo c = new System.Globalization.CultureInfo("en-us", false)
System.Globalization.TextInfo t = c.TextInfo;

return t.ToTitleCase(s);
}

필요한 모든 것이 여기에 많은 복잡성이있는 것 같습니다.

    /// <summary>
    /// Returns the input string with the first character converted to uppercase if a letter
    /// </summary>
    /// <remarks>Null input returns null</remarks>
    public static string FirstLetterToUpperCase(this string s)
    {
        if (string.IsNullOrWhiteSpace(s))
            return s;

        return char.ToUpper(s[0]) + s.Substring(1);
    }

주목할만한 점 :

  1. 확장 방법입니다.

  2. 입력이 null, 비어 있거나 공백이면 입력이 그대로 반환됩니다.

  3. String.IsNullOrWhiteSpace 는 .NET Framework 4에서 도입되었습니다. 이전 프레임 워크에서는 작동하지 않습니다.


string emp="TENDULKAR";
string output;
output=emp.First().ToString().ToUpper() + String.Join("", emp.Skip(1)).ToLower();

"최대 성능"답변을 제공하고 싶었습니다. 제 생각에는 "최대 성능"답변이 모든 시나리오를 포착하고 해당 시나리오에 대한 질문 설명에 대한 답변을 제공합니다. 그래서, 여기 내 대답이 있습니다. 이러한 이유로

  1. IsNullOrWhiteSpace는 공백이거나 null / 빈 문자열 인 문자열을 설명합니다.
  2. .Trim ()은 문자열의 앞뒤에서 공백을 제거합니다.
  3. .First ()는 ienumerable (또는 string)의 첫 문자를 사용합니다.
  4. 대문자 일 수있는 문자인지 확인해야합니다.
  5. 그런 다음 길이가 표시되어야하는 경우에만 나머지 문자열을 추가합니다.
  6. .Net 모범 사례에 따라 System.Globalization.CultureInfo에 문화를 제공해야합니다.
  7. 옵션 매개 변수로 제공하면 매번 선택한 문화권을 입력 할 필요없이이 방법을 완전히 재사용 할 수 있습니다.

    public static string capString(string instring, string culture = "en-US", bool useSystem = false)
    {
        string outstring;
        if (String.IsNullOrWhiteSpace(instring))
        {
            return "";
        }
        instring = instring.Trim();
        char thisletter = instring.First();
        if (!char.IsLetter(thisletter))
        {
            return instring;   
        }
        outstring = thisletter.ToString().ToUpper(new CultureInfo(culture, useSystem));
        if (instring.Length > 1)
        {
            outstring += instring.Substring(1);
        }
        return outstring;
    }
    

아래 방법이 최선의 해결책이라고 생각합니다.

    class Program
{
    static string UppercaseWords(string value)
    {
        char[] array = value.ToCharArray();
        // Handle the first letter in the string.
        if (array.Length >= 1)
        {
            if (char.IsLower(array[0]))
            {
                array[0] = char.ToUpper(array[0]);
            }
        }
        // Scan through the letters, checking for spaces.
        // ... Uppercase the lowercase letters following spaces.
        for (int i = 1; i < array.Length; i++)
        {
            if (array[i - 1] == ' ')
            {
                if (char.IsLower(array[i]))
                {
                    array[i] = char.ToUpper(array[i]);
                }
            }
        }
        return new string(array);
    }

    static void Main()
    {
        // Uppercase words in these strings.
        const string value1 = "something in the way";
        const string value2 = "dot net PERLS";
        const string value3 = "String_two;three";
        const string value4 = " sam";
        // ... Compute the uppercase strings.
        Console.WriteLine(UppercaseWords(value1));
        Console.WriteLine(UppercaseWords(value2));
        Console.WriteLine(UppercaseWords(value3));
        Console.WriteLine(UppercaseWords(value4));
    }
}

Output

Something In The Way
Dot Net PERLS
String_two;three
 Sam

심판


이것은이 첫 글자와 공백 뒤에 소문자를 제외한 모든 글자를 대문자로합니다.

public string CapitalizeFirstLetterAfterSpace(string input)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder(input);
    bool capitalizeNextLetter = true;
    for(int pos = 0; pos < sb.Length; pos++)
    {
        if(capitalizeNextLetter)
        {
            sb[pos]=System.Char.ToUpper(sb[pos]);
            capitalizeNextLetter = false;
        }
        else
        {
            sb[pos]=System.Char.ToLower(sb[pos]);
        }

        if(sb[pos]=' ')
        {
            capitalizeNextLetter=true;
        }
    }
}

다음 코드를 사용하십시오.

string  strtest ="PRASHANT";
strtest.First().ToString().ToUpper() + strtest.Remove(0, 1).ToLower();

여기에 주어진 해결책 중 어느 것도 문자열 앞에 공백을 처리하지 않는 것 같습니다.

이것을 생각으로 추가하기 만하면됩니다.

public static string SetFirstCharUpper2(string aValue, bool aIgonreLeadingSpaces = true)
{
    if (string.IsNullOrWhiteSpace(aValue))
        return aValue;

    string trimmed = aIgonreLeadingSpaces 
           ? aValue.TrimStart() 
           : aValue;

    return char.ToUpper(trimmed[0]) + trimmed.Substring(1);
}   

처리해야합니다 this won't work on other answers(문장에 공백이 있음). 공간 트리밍이 마음에 들지 않으면 false두 번째 매개 변수로 전달하십시오 (또는 기본값을으로 변경하고 공백을 처리하려면 false전달 true하십시오)


FluentSharp는 lowerCaseFirstLetter이것을 수행 하는 방법을 가지고 있습니다

https://github.com/o2platform/FluentSharp/blob/700dc35759db8e2164771a71f73a801aa9379074/FluentSharp.CoreLib/ExtensionMethods/System/String_ExtensionMethods.cs#L575


가장 빠른 방법입니다.

public static unsafe void ToUpperFirst(this string str)
{
    if (str == null) return;
    fixed (char* ptr = str) 
        *ptr = char.ToUpper(*ptr);
}

원래 문자열을 변경하지 않고 :

public static unsafe string ToUpperFirst(this string str)
{
    if (str == null) return null;
    string ret = string.Copy(str);
    fixed (char* ptr = ret) 
        *ptr = char.ToUpper(*ptr);
    return ret;
}

전나무 편지를 대문자로 표시하는 가장 쉬운 방법은 다음과 같습니다.

1- Sytem.Globalization 사용;

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

  myTI.ToTitleCase(textboxname.Text)

`


다음 기능은 모든 방법에 적합합니다.

static string UppercaseWords(string value)
{
    char[] array = value.ToCharArray();
    // Handle the first letter in the string.
    if (array.Length >= 1)
    {
        if (char.IsLower(array[0]))
        {
            array[0] = char.ToUpper(array[0]);
        }
    }
    // Scan through the letters, checking for spaces.
    // ... Uppercase the lowercase letters following spaces.
    for (int i = 1; i < array.Length; i++)
    {
        if (array[i - 1] == ' ')
        {
            if (char.IsLower(array[i]))
            {
                array[i] = char.ToUpper(array[i]);
            }
        }
    }
    return new string(array);
}

나는 그것을 여기 에서 발견했다


위의 Carlos의 질문을 확장하여 여러 문장을 대문자로 작성하려면이 코드를 사용할 수 있습니다.

    /// <summary>
    /// Capitalize first letter of every sentence. 
    /// </summary>
    /// <param name="inputSting"></param>
    /// <returns></returns>
    public string CapitalizeSentences (string inputSting)
    {
        string result = string.Empty;
        if (!string.IsNullOrEmpty(inputSting))
        {
            string[] sentences = inputSting.Split('.');

            foreach (string sentence in sentences)
            {
                result += string.Format ("{0}{1}.", sentence.First().ToString().ToUpper(), sentence.Substring(1)); 
            }
        }

        return result; 
    }

최근 비슷한 요구 사항이 있었고 LINQ 함수 Select ()가 색인을 제공한다는 것을 기억했습니다.

string input;
string output;

input = "red house";
output = String.Concat(input.Select((currentChar, index) => index == 0 ? Char.ToUpper(currentChar) : currentChar));
//output = "Red house"

매우 자주 필요하기 때문에 문자열 유형에 대한 확장 메소드를 만들었습니다.

public static class StringExtensions
{
    public static string FirstLetterToUpper(this string input)
    {
        if (string.IsNullOrEmpty(input))
            return string.Empty;
        return String.Concat(input.Select((currentChar, index) => index == 0 ? Char.ToUpper(currentChar) : currentChar));
    }
}

첫 글자 만 대문자로 변환되며 나머지 문자는 모두 터치하지 않습니다. 다른 문자를 소문자로 사용해야하는 경우 색인> 0에 대해 Char.ToLower (currentChar)를 호출하거나 처음부터 전체 문자열에서 ToLower ()를 호출 할 수도 있습니다.

성능과 관련하여 코드를 Darren의 솔루션과 비교했습니다. 내 컴퓨터에서 Darren의 코드는 약 2 배 빠릅니다 .char 배열의 첫 번째 문자 만 직접 편집하기 때문에 놀랍지 않습니다. 따라서 가능한 가장 빠른 솔루션이 필요한 경우 Darren의 코드를 사용하는 것이 좋습니다. 다른 문자열 조작을 통합하려면 입력 문자열의 문자를 터치하는 람다 함수의 표현력을 갖는 것이 편리 할 수 ​​있습니다.이 기능을 쉽게 확장 할 수 있으므로이 솔루션을 여기에 남겨 둡니다.


문자열이 null이 아닌지 확인한 다음 첫 번째 문자를 대문자로, 나머지는 소문자로 변환하십시오.

public static string FirstCharToUpper(string str)
{
    return str?.First().ToString().ToUpper() + input?.Substring(1).ToLower();
}

이 방법을 사용하면 모든 단어의 첫 번째 문자를 초과 할 수 있습니다.

예 "HeLlo wOrld"=> "Hello World"

public static string FirstCharToUpper(string input)
{
    if (String.IsNullOrEmpty(input))
        throw new ArgumentException("Error");
    return string.Join(" ", input.Split(' ').Select(d => d.First().ToString().ToUpper() +  d.ToLower().Substring(1)));
}

참고 URL : https://stackoverflow.com/questions/4135317/make-first-letter-of-a-string-upper-case-with-maximum-performance



반응형