C# - How to sort a list of strings using last character by ignoring special character if any at the end

Viewed 2857

Below is the logic that i tried to implement and able to sort it but need to figure out to ignore special characters in it

My Logic:

  • Reversed string in a list
  • Sorted in ascending order
  • Again reversed back sorted strings &
  • Finally returned as a string by joining with ~ delimiter.

        List<String> inputLst= new List<String>() { "Bananas!", "Cherry2",
        "Mango","Apples", "Grape$", "Guava" };
    
        List<String> sortList = new List<String>();
        List<String> outputList = new List<String>();
    
        foreach (String str in inputLst)
        {
            sortList.Add(new String(str.ToCharArray().Reverse().ToArray()));
        }
        sortList.Sort();
    
        foreach (String str in sortList)
        {
            outputList.Add(new String(str.ToCharArray().Reverse().ToArray()));
        }
        Return String.Join("~", outputList);
    

Output i got is Bananas!~Grape$~Cherry2~Guava~Mango~Apples

Expected output should be Guava~Grape$~Mango~Bananas!~Apples~Cherry2

Could anyone please suggest me optimized solution to sort a list by last character by ignoring special characters? Here i used 2 lists for string reversals, can it be done in more efficient way? Note: without using LINQ pls.

3 Answers
Related