0

I am a beginner and I want to write a program that takes a string from the user and reverses every word but not the whole sentence. For example if "gnimmargorP si nuf" is the input, output should be "Programming is fun". not "fun is programming" what can I do or change to make the program see the words of the sentences

I wrote:

import java.util.Scanner;

public class Lab06
{
     public static void main( String[] args )
     {
          Scanner scan = new Scanner( System.in );
          String line;
          // REVERSER

          System.out.println();
          System.out.println("Please enter a line");
          line = scan.nextLine();
          System.out.println( "The reverse of the sentence is:");
          System.out.println(reverse(line));
     }

     public static String reverse( String s )
     {
          String answer = "";
          int length = s.length();
          for ( int i = length - 1; i >= 0; i--)
          {
               answer = answer + s.charAt(i);

          }
          return answer;
     }
}
Chirag Parmar
  • 833
  • 11
  • 26
  • 3
    You can use line.split(" ") to split the line into words, and run reverse on the word separately. – Eran Nov 22 '16 at 06:56

6 Answers6

3

try this code

    String input = "gnimmargorP si nuf";
    String[] arr = input.split(" ");
    for (String word : arr) {
        StringBuilder out = new StringBuilder(word).reverse().append(" ");
        System.out.print(out.toString());
    }

Of course you can use your own reverse method

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
3

I'll add a Java 8 example in the mix for conciseness' sake.

Arrays.stream("gnimmargorP si nuf".split(" "))
      .forEach(s -> System.out.printf("%s ",  new StringBuilder(s).reverse()));

You get a stream from the array created by splitting the string around " "s, iterate over each word, and print its reverse followed by a space.

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75
1

You can split the entered sentence with whitespaces and apply your reverse method for each word. Finally you can concatenate them back to one string.

Areca
  • 1,292
  • 4
  • 11
  • 21
  • but I dont know the sentence before the user inputs it how can I know where to split beforehand – Ekin Alparslan Nov 22 '16 at 06:58
  • @EkinAlparslan, `split(String)` do it for you, it returns an array. Areca Please add more information on the methods in this answer ;) – AxelH Nov 22 '16 at 07:00
0

Try following code. Please comment if you dont understand anything:

import java.util.Scanner;

public class Lab06 
{
    public static void main( String[] args )
    { 
         Scanner scan = new Scanner( System.in );
         String line;

         // REVERSER 
         try{
             System.out.println();
             System.out.println("Please enter a line:");
             line = scan.nextLine();
             StringBuilder answer = new StringBuilder(line.length());


             String[] words = line.split("\\s+");
             for(String word : words){
                 answer.append(reverse(word)).append(" ");
             }
             System.out.println( "The reverse of the sentence is:");
             System.out.println(answer);
         }catch(Exception e){

         }finally{
             scan.close();
         }
    } 


    public static String reverse( String input )
    { 
        String answer = "";
        int length = input.length();
        for ( int i = length - 1; i >= 0; i--) { 
             answer = answer + input.charAt(i);
        } 
        return answer;
    }
}
Chirag Parmar
  • 833
  • 11
  • 26
0

You need to follow the below steps:

(1) Split the words using space delimiter

(2) Iterate each word

(3) Iterate each character and add each character to stringBuilder object

(4) Suffix space again for each word

(5) Convert stringBuilder object to string again

You can refer the below code with comments:

public static String reverse(String s ) {
        String[] words = s.split(" ");//split the words using space

        StringBuilder sb = new StringBuilder();
        for(String word : words) {//Iterate each word
            for(int i=word.length()-1;i>=0;i--) {//Iterate each character
                sb.append(word.charAt(i));
            }
            sb.append(" ");//suffix space again after each word
        }
        return sb.toString();//convert to string again
    }
Vasu
  • 21,832
  • 11
  • 51
  • 67
-1

You can split the inputted String, use StringBuilder's reverse() method, and concatenate it back to one String.

public static String reverse(String s) {
    StringBuilder answer = new StringBuilder();

    if (null == s || 0 == s.length()) {
        return answer.toString();
    }

    String[] words = s.split(" ");

    for (int i = 0, lastIndex = s.length() - 1; i < s.length(); i++) {
        StringBuilder sb = new StringBuilder(words[i]);

        sb.reverse();

        if (i != lastIndex) {
            sb.append(" ");
        }

        answer.append(sb.toString());
    }

    return answer.toString();
}
  • I would think you might as well use another `StringBuilder` for the `answer`. If you're willing to create and kill one every iteration for the convenience of `reverse()`, one more to use where it's most useful couldn't hurt. – ChiefTwoPencils Nov 23 '16 at 02:21