S
S
Samaif2015-02-16 22:24:08
Arrays
Samaif, 2015-02-16 22:24:08

How to sort the elements of a string array so that the elements are displayed in ascending order?

For example "a""abc""ab" output "a""ab""abc"

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Espleth, 2015-02-16
@Espleth

And standard sorting does not want to sort them?
If not, then make your own IComparer and pass it to the standard sort.

class StringComparer : IComparer<string>
    {
        public int Compare(string str1, string str2)
        {
            for (int i = 0; i < str1.Count; ++i)
            {
                if (str1[i] > str2[i])
                {
                    return 1;
                }
                if (str1[i] < str2[i])
                {
                    return -1;
                }
            }
            return 0;
        }
    }

Somehow it will look like this. It still needs to be written there in case of different line lengths, etc., but I hope you can handle it
. And yes, Google will help

S
Sumor, 2015-02-16
@Sumor

Ordinary Sort on an array .

V
Valery Okhotnikov, 2015-02-17
@vox13

using System;

namespace strsort
{
  class Program
  {
    public static void Main(string[] args)
    {
      //данный массив строк
      string[] m = {"a","abc","ab"};
      
      Console.WriteLine("Массив до сортировки:");
      foreach (string s in m)
        Console.WriteLine(s);
      
      Array.Sort(m);
      Console.WriteLine();
      
      Console.WriteLine("Массив после сортировки:");
      foreach (string s in m)
        Console.WriteLine(s);
      
      Console.Write("Press any key to continue . . . ");
      Console.ReadKey(true);
    }
  }
}

A
Alexey, 2015-02-17
@HaJIuBauKa

Discover LINQ:

using System;
using System.Linq;
          
public class Program
{
  public static void Main()
  {
    string[] __sa = {"a", "abc", "ab"};
    Console.WriteLine(String.Join(" ", __sa.OrderBy(x => x.Length).ToArray()));
  }
}

https://dotnetfiddle.net/ORcFLn
And yes - regular sorting works.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question