Home > Enterprise >  Sorting string with its first letter
Sorting string with its first letter

Time:05-16

I have following string

string strings = "\"Johnson\", \"Williams\", \"Brown\", \"Jones\"";

What I am trying to do is to sort this string alphabetically like this:

  • Brown
  • Johnson Jones
  • Williams

I have no idea what to do and how to solve this. What should I do with it

CodePudding user response:

Approach with Split and Join

string strings = "\"Johnson\", \"Williams\", \"Brown\", \"Jones\"";
string result = string.Join(", ", strings.Split().Select(x => x.Trim(',')).OrderBy(x => x));

CodePudding user response:

You can try quering the given string:

  • Split on ',' to have separeted words
  • Get rid of spaces and quotation marks with a help of Trim().
  • Order the words
  • As I can see you want to Group words by the 1st letters
  • Finally, lets materialize the result as an array

Code:

  string strings = "\"Johnson\", \"Williams\", \"Brown\", \"Jones\"";

  string[] result = strings
    .Split(',')
    .Select(word => word.Trim(' ', '"'))
    .Where(word => !string.IsNullOrEmpty(word))
    .OrderBy(word => word)
    .GroupBy(word => word[0])
    .Select(group => string.Join(" ", group))
    .ToArray();

If you want to obtain string instead of array, put Join:

  string myString = string.Join(" ", result);

Let's have a look:

  Console.Write(string.Join(Environment.NewLine, result));

Outcome:

Brown
Johnson Jones
Will

CodePudding user response:

Assuming you are using a list with multiple strings, we can use a bubble sorting algorithm to sort the list.

Loop through the list swapping positions if the second string has a lower letter than the first one. Loop until the list is fully sorted.

  • Related