Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

how to reverse a particular string in a sentence based on user input

for example, if the user put <hello world 1> it will return hello dlorw , so how to break the sentence? thanks

1 Answer

Sue's link to StackOverflow is interesting. But as far as I can see the solutions there reverse all the words in a String, not just the one the users indicate they want reversed.

Here's one way -- as always, there are other ways to do this:

import java.util.Scanner;

class ReverseWordInString {
   public static void main(String[] args) {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter words, space separated, followed by the number ");
      System.out.print("of the word you want reversed (starting with 0): ");
      String string = in.nextLine();
      //String string = "hello world 1";  //use if you don't want Scanner
      //String string = "now is the time for all good men 3";   //2nd test case

      reverseWord(string);
   }

   public static void reverseWord(String s) {
      String[] words = s.split(" ");
      int toReverse = Integer.parseInt(words[words.length - 1]);  //get index of word to reverse
      for (int i = 0; i < words.length; i++) {
         if (i == toReverse)  {  
            System.out.print(new StringBuilder(words[toReverse]).reverse().toString() + " ");
         } else if (i == words.length - 1) {
            //ignore
         } else {
            System.out.print(words[i] + " ");
         }
      }       
   }

}

Note: I would strongly suggest that you not have the user indicate the word they want reversed as part of the input String, but rather as separate input.

Your correct. I am no Java expert however left it there because it could point them in the right direction. I figured they could isolate that 1 word somehow and then do it. It seems like you figured that part out. Nice work.