简体   繁体   English

使用循环反转字符串

[英]Using loops to reverse a string

I am having trouble doing a task whereby someone enters a multiple line string, and I read the string and output each word in reverse in the exact same spot (whitespace and line breaks the same).我在执行某人输入多行字符串的任务时遇到了麻烦,我在完全相同的位置(空格和换行符相同)读取了字符串和 output 每个单词。 After inputting how many words the user wants to reverse they type "done" to basically stop the loop.在输入用户想要反转多少个单词后,他们键入“完成”以基本上停止循环。

Eg.例如。 input:输入:

hey hello
world
done

output: output:

yeh olleh
dlrow

heres my code in which the loop never stops and does not scan the second line.这是我的代码,其中循环永远不会停止并且不会扫描第二行。

import java.util.Scanner;

public class LabProgram {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

        String input = scnr.next();
        String reverse = "";

        while (!input.equals("done")) {
            for (int i = input.length() - 1; i >= 0; i--) {
                reverse = reverse + input.charAt(i);
            }
            System.out.println(reverse);
        }
    }
}

The loop you want to print the input word reversed is this:您要打印输入单词的循环是这样的:

Scanner scnr = new Scanner(System.in);
String input = scnr.next();

for (int i=input.length()-1; i >= 0; --i) {
    System.out.print(input.charAt(i));
}

Note that I use print() rather than println() , as you want to view the reversed input on the same line.请注意,我使用print()而不是println() ,因为您想在同一行上查看反向输入。

As for accepting user inputs while the loop is running, if you want that, you should break to stop printing based on some user input.至于在循环运行时接受用户输入,如果需要,您应该根据某些用户输入break以停止打印。

You were close.你很亲密。 I simply changed your outer while loop slightly to both take in the input and check for the termination string.我只是稍微更改了您的外部 while 循环,以同时接收输入并检查终止字符串。 It will now reverse what ever you type in but will stop if you type in done .它现在将反转您输入的内容,但如果您输入done将停止。

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    String input;
    while (!(input = scnr.nextLine()).equalsIgnoreCase("Done")) {
    
    String reverse = "";
    
        for (int i = input.length() - 1; i >= 0; i--) {
            reverse = reverse + input.charAt(i);
        }
        System.out.println(reverse);
    }
}

To simplify the code, you can use an enhanced for loop instead of reversed for loop and swap the summands inside:为了简化代码,您可以使用增强的 for 循环而不是反向 for 循环并交换里面的和:

String str = "hello world", reverse = "";

for (char ch : str.toCharArray())
    reverse = ch + reverse;

System.out.println(reverse); // dlrow olleh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM