How to sort the words in a string with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class SortTheWordsInAString_CSharp
{
    public static string SortTheWordsInAString(string s) {
        List<string> arr = new List<string>();

        string[] tokens = s.Split(' ');
        arr.AddRange(tokens);

        arr.Sort();

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (string str in arr) {
            sb.Append(str).Append(" ");
        }

        if (sb.Length > 0) {
            sb.Length--; // Remove the last space
        }

        return sb.ToString();
    }

    public static void Main(string[] args)
    {
        string s = "php c java c++ python c#";

        s = SortTheWordsInAString(s);

        Console.WriteLine(s);
    }
}


    
/*
run:
    
c c# c++ java php python
    
*/

 



answered Jul 29, 2024 by avibootz

Related questions

...