>백엔드 개발 >C++ >숫자 값의 우선 순위를 지정하면서 문자열 배열을 알파벳순으로 정렬하는 방법은 무엇입니까?

숫자 값의 우선 순위를 지정하면서 문자열 배열을 알파벳순으로 정렬하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-12-30 11:15:21565검색

How to Sort a String Array Alphabetically While Prioritizing Numerical Values?

문자열 배열에서 숫자 값의 우선순위를 지정하면서 알파벳 순서 유지

문자열을 알파벳순으로 정렬하는 것은 표준 작업이지만, 문자열이 숫자 순서를 유지하면서 숫자를 나타내기도 합니까? 다음은 이 문제를 해결하는 솔루션입니다.

다음 코드를 고려하세요.

string[] things= new string[] { "105", "101", "102", "103", "90" };

foreach (var thing in things.OrderBy(x => x))
{
    Console.WriteLine(thing);
}

이 코드는 숫자 문자열 배열을 알파벳순으로 정렬하려고 시도하지만 출력은 원하는 것과 다릅니다.

101, 102, 103, 105, 90

예상 출력을 얻으려면:

90, 101, 102, 103, 105

사용자 정의를 전달해야 합니다. OrderBy에 비교합니다. Enumerable.OrderBy를 사용하면 정렬을 위한 사용자 정의 비교자를 지정할 수 있습니다.

다음은 SemiNumericComparer를 사용한 구현입니다.

string[] things = new string[] { "paul", "bob", "lauren", "007", "90" };

foreach (var thing in things.OrderBy(x => x, new SemiNumericComparer()))
{    
    Console.WriteLine(thing);
}

SemiNumericComparer 클래스는 문자열이 숫자인지 확인하는 메서드를 정의하고 다음을 제공합니다. 비교 방법:

public class SemiNumericComparer: IComparer<string>
{
    /// <summary>
    /// Method to determine if a string is a number
    /// </summary>
    /// <param name="value">String to test</param>
    /// <returns>True if numeric</returns>
    public static bool IsNumeric(string value)
    {
        return int.TryParse(value, out _);
    }

    /// <inheritdoc />
    public int Compare(string s1, string s2)
    {
        const int S1GreaterThanS2 = 1;
        const int S2GreaterThanS1 = -1;

        var IsNumeric1 = IsNumeric(s1);
        var IsNumeric2 = IsNumeric(s2);

        if (IsNumeric1 &amp;&amp; IsNumeric2)
        {
            var i1 = Convert.ToInt32(s1);
            var i2 = Convert.ToInt32(s2);

            if (i1 > i2)
            {
                return S1GreaterThanS2;
            }

            if (i1 < i2)
            {
                return S2GreaterThanS1;
            }

            return 0;
        }

        if (IsNumeric1)
        {
            return S2GreaterThanS1;
        }

        if (IsNumeric2)
        {
            return S1GreaterThanS2;
        }

        return string.Compare(s1, s2, true, CultureInfo.InvariantCulture);
    }
}

배열에 적용할 경우 문자열의 경우 SemiNumericComparer는 먼저 문자열을 알파벳순으로 정렬한 다음 숫자 값으로 정렬하여 원하는 출력을 제공합니다.

위 내용은 숫자 값의 우선 순위를 지정하면서 문자열 배열을 알파벳순으로 정렬하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.