Search code examples
javastringreversestringbuilderstringbuffer

Interview Q: Reverse a word "Amazon" from string "I am working for Amazon"


I am able to reverse a string. For example, I can reverse "reverse a string" to "esrever a gnirts". I am trying to create a function that reverse a word from a sentence. I only want "Amazon" in reverse.Please help/suggest.

String = "I am working for Amazon" ; Required output - "I am working for nozamA"

Please help/suggest. TIA


Solution

  • input :

    String sentence = "I am working for Amazon";
    String word ="Amazon";
    

    with following step you can get desire output

    String reversed = new StringBuilder(word).reverse().toString();
    String output = sentence.replace(word, reversed);