通过 for 循环反转带有 spaces.going 的字符串

Reverse a string with spaces.going through for loop

在这个练习中,我要反转一个字符串。我能够让它工作,但它不适用于空格。例如 Hello 那里只会输出 olleH。我尝试做一些类似被注释掉的事情,但无法让它工作。

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);
}
}

谁能帮忙解决一下,谢谢。

您的 reverse 方法是正确的,您正在调用 Scanner.next() 读取一个单词(下一次,打印 input)。对于您描述的行为,更改

String input = scan.next();

String input = scan.nextLine();

您也可以这样初始化扫描器:

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

以便它使用换行符分隔输入。

通过这种方法,您可以使用 sc.next() 来获取字符串中的整行。

更新

正如 documentation 所说:

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.

取自同一页面的示例:

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

所有这些都是使用 useDelimiter method 制作的。

在这种情况下,当你 want/need 阅读整行时,你的 useDelimiter 必须有一个允许阅读整行的模式,这就是你可以使用 \n 的原因,所以你可以这样做:

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