How to remove a random word from a string in Java

1 Answer

0 votes
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        String str = "I'm not clumsy The floor just hates me";

        String result = removeRandomWord(str);

        System.out.println(result);
    }

    static String removeRandomWord(String input) {
        Random random = new Random();
        
        String[] words = input.split(" ");
        if (words.length == 0) return input;

        int randomIndex = random.nextInt(words.length);
        
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            if (i != randomIndex) {
                result.append(words[i]).append(" ");
            }
        }
        
        return result.toString().trim();
    }
}



/*
run:

I'm not The floor just hates me

*/

 



answered May 4 by avibootz
...