Dominick
Dominick

Reputation: 23

Reverse a string with spaces.going through for loop

In this exercise I am to reverse a string. I was able to make it work, though it will not work with spaces. For example Hello there will output olleH only. I tried doing something like what is commented out but couldn't get it to work.

import java.util.Scanner;

class reverseString{
  public static void main(String args[]){
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String input = scan.next();
    int length = input.length();
    String reverse = "";
    for(int i = length - 1; i >= 0; i--){
        /*if(input.charAt(i) == ' '){
            reverse += " ";
        }
        */
        reverse += input.charAt(i); 
    }
    System.out.print(reverse);
}
}

Can someone please help with this, thank you.

Upvotes: 0

Views: 1109

Answers (2)

Dazak
Dazak

Reputation: 1033

You can also initialize the Scanner this way:

Scanner sc = new Scanner(System.in).useDelimiter("\\n");

So that it delimits input using a new line character.

With this approach you can use sc.next() to get the whole line in a String.

Update

As the documentation says:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

An example taking from the same page:

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close(); 

prints the following output:

1
2
red
blue

All this is made using the useDelimiter method.

In this case as you want/need to read the whole line, then your useDelimiter must have a pattern that allows read the whole line, that's why you can use \n, so you can do:

Scanner sc = new Scanner(System.in).useDelimiter("\\n");

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

Your reverse method is correct, you are calling Scanner.next() which reads one word (next time, print the input). For the behavior you've described, change

String input = scan.next();

to

String input = scan.nextLine();

Upvotes: 2

Related Questions