How to move a word to the end of a string in C#

1 Answer

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

class Program
{
    static string MoveWordToEnd(string s, string word)
    {
        // Split on whitespace
        var parts = s.Split((char[])null, StringSplitOptions.RemoveEmptyEntries)
                     .ToList();

        // Remove the first occurrence
        if (parts.Remove(word)) {
            parts.Add(word);
        }

        // Rebuild the string
        return string.Join(" ", parts);
    }

    static void Main()
    {
        string s = "Would you like to know more? (Explore and learn)";
        string word = "like";

        string result = MoveWordToEnd(s, word);
        Console.WriteLine(result);
    }
}



/*
run:

Would you to know more? (Explore and learn) like

*/

 



answered Feb 5 by avibootz
...