How to move a word to the end of a string in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static String moveWordToEnd(String s, String word) {
        List<String> parts = new ArrayList<>(Arrays.asList(s.split("\\s+")));

        if (parts.remove(word)) {   // remove returns true if found
            parts.add(word);
        }

        return String.join(" ", parts);
    }

    public static void main(String[] args) {
        String s = "Would you like to know more? (Explore and learn)";
        String word = "like";

        String result = moveWordToEnd(s, word);
        System.out.println(result);
    }
}



/*
run:

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

*/

 



answered Feb 3 by avibootz
...