Home > Backend Development > C++ > How to Sort a String Array Alphabetically While Prioritizing Numerical Values?

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

Patricia Arquette
Release: 2024-12-30 11:15:21
Original
557 people have browsed it

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

Maintaining Alphabetical Order while Prioritizing Numeric Values in String Arrays

Sorting strings alphabetically is a standard task, but how do you handle scenarios where strings also represent numbers while maintaining the numerical order? Here's a solution that addresses this challenge.

Consider the following code:

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

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

This code attempts to sort an array of numeric strings alphabetically, but the output is not as desired:

101, 102, 103, 105, 90
Copy after login

To achieve the expected output:

90, 101, 102, 103, 105
Copy after login

you need to pass a custom comparer into OrderBy. Enumerable.OrderBy allows you to specify a custom comparer for sorting.

Here's an implementation using a SemiNumericComparer:

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

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

The SemiNumericComparer class defines a method to determine whether a string is numeric and provides a comparison method:

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);
    }
}
Copy after login

When applied to the array of strings, the SemiNumericComparer sorts the strings first by alphabetical order and then by numerical value, providing the desired output.

The above is the detailed content of How to Sort a String Array Alphabetically While Prioritizing Numerical Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template