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

1 Answer

0 votes
public class Main {

    public static String move_first_word_to_end_of_string(String s) {
        String[] parts = s.trim().split("\\s+");

        if (parts.length <= 1) {
            return s.trim();
        }

        StringBuilder sb = new StringBuilder();

        // Append all except the first
        for (int i = 1; i < parts.length; i++) {
            sb.append(parts[i]).append(" ");
        }

        // Append the first word at the end
        sb.append(parts[0]);

        return sb.toString();
    }

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

        System.out.println(result);
    }
}



/*
run:

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

*/

 



answered Feb 5 by avibootz
...