Search code examples
javastringswap

How to swap the order of specific words in a string?


I have a string:

String test = "This is a test string of many words and more";

Also I have a list of unique words that needs to be swapped:

List<String> words = Arrays.asList("is", "test", "words", "more");

the list contains words in the correct order extracted from original string. Number of words to reverse order is varying. The result must look like this: all of words in a list are reversed and put in original string

"This more a words string of many test and is"

Splitting by space would not work because this is a general solution to specific problem.


Solution

  • Try this:

    public static void main(String[] args) {
    
        String test = "This is a test string of many words and more";
        List<String> words = Arrays.asList("is", "test", "words", "more");
        int size = words.size();
        for (int i = 0; i < size / 2; i++) {
            String firstWord = " "+words.get(i)+" ";
            String secondWord = " "+words.get(size - 1 - i)+" ";
            String temp = "####";
            test = test.replace(firstWord, temp);
            test = test.replace(secondWord, firstWord);
            test = test.replace(temp, secondWord);
        }
        System.out.println(test);
    }