Placing the smallest integer

string strArr="5,3,8,1,9,2,0,6,4,7";

I would like to reorder the numbers so that the result looks like this:

string result ="0,1,2,3,4,5,6,7,8,9";

Any idea?

+3
source share
5 answers

Split, sort and merge:

string[] nums = strArr.Split(',');
Array.Sort(nums);
string result = String.Join(",", nums);

Or:

string result =
  String.Join(",",
    strArr.Split(',')
    .OrderBy(s => s)
    .ToArray()
  );

If you have a string with large numbers that you need to sort numerically, you cannot sort them as strings, for example, "2"> "1000". You convert each substring to a number, sort, and then convert back:

string result =
  String.Join(",",
    strArr
      .Split(',')
      .Select(s => Int32.Parse(s))
      .OrderBy(n => n)
      .Select(n => n.ToString())
      .ToArray()
  );

Or, as suggested by masta, parse the lines in the sort:

string result =
  String.Join(",",
    strArr
      .Split(',')
      .OrderBy(s => Int32.Parse(s))
      .ToArray()
  );
+20
source

A shorter version of one of the versions in Guffa responds:

var res = String.Join(",", str.Split(',').OrderBy(y => int.Parse(y)).ToArray());
+3
source

:

string strArr = "5,3,8,1,9,2,0,6,4,7";
string[] sArr = strArr.Split(',');
Array.Sort(sArr);
string result = string.Join(",", sArr);
+2

string string.split(char[]).

With this array, you can call a method Array.Sort(T)that will sort the elements in ascending order (for your example).

With this sorted array, you can call String.Join(string, object[])to concatenate it again into a string.

0
source
string arr = "5,3,8,1,9,2,0,6,4,7";
string result = arr.Split(',').OrderBy(str => Int32.Parse(str)).Aggregate((current, next) => current + "," + next);
0
source

Source: https://habr.com/ru/post/1768946/


All Articles