How to reverse a word in a string with Java

1 Answer

0 votes
public class ReverseWordInString {

    public static void reverseWord(StringBuilder str, String word) {
        int pos = str.indexOf(word);
        if (pos != -1) {
            int end = pos + word.length();
            str.replace(pos, end, new StringBuilder(word).reverse().toString());
        }
    }

    public static void main(String[] args) {
        StringBuilder str = new StringBuilder("C++ C Java Python PHP C#");
        String word = "Java";

        reverseWord(str, word);

        System.out.println(str);
    }
}



/*
run:

C++ C avaJ Python PHP C#

*/

 



answered Sep 26 by avibootz
...