How to remove a random word from a string in C#

1 Answer

0 votes
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string str = "I'm not clumsy The floor just hates me";
        
        string result = RemoveRandomWord(str);
        
        Console.WriteLine(result);
    }

    static string RemoveRandomWord(string input) {
        Random random = new Random();
        
        string[] words = input.Split(' ');
        if (words.Length == 0) return input;

        int randomIndex = random.Next(words.Length);
        words = words.Where((word, index) => index != randomIndex).ToArray();
        
        return string.Join(" ", words);
    }
}



/*
run:
 
I'm not clumsy The floor just me
 
*/

 



answered May 4, 2025 by avibootz
...