【问题标题】:How can I reverse a string word by word without using arrays, split() or StringBuilder如何在不使用数组、split() 或 StringBuilder 的情况下逐字反转字符串
【发布时间】:2020-12-30 08:26:08
【问题描述】:

我试图在不使用数组split()StringBuilder 的情况下逐字反转字符串。到目前为止,这是我的代码。它有效,但我的输出不是我想要的。请参阅我的图像以获取输出。 我希望我的程序在新行上输出每个单词。还要注意窗帘上缺少字母“n”,最后两个单词之间没有空格。我该如何解决这个问题?

public static void main(String[] args) {

    String sentence = new String("pay no attention to that man behind the curtain");
    String reversed = "";

    int endIndex = sentence.length()-1;
    for(int i = endIndex; i >= 0; i--) {
        if(sentence.charAt(i) == ' ') {
            reversed += sentence.substring(i, endIndex);
            endIndex = i;
        }
    }
    reversed += sentence.substring(0, endIndex);
    System.out.println(reversed);
}

【问题讨论】:

  • StringBuilder 有一个专门的方法。
  • 调试您的程序以查看该字母丢失的位置。

标签: java string algorithm reverse


【解决方案1】:

首先,有一个更好的方法来反转单词。但是让我们看看你的程序。

我希望我的程序在新行上输出每个单词。

如果您想在新行中打印每个单词,您可以将每个单词添加到单词列表中并在新行中打印每个单词,或者您可以在每个单词的末尾添加“\n”。

还要注意窗帘上缺少字母“n”并且没有 最后两个单词之间的空格。

这是因为endIndexsentence.length()-1 开始,Java 中的substring 通过从 startIndex 提取到 endIndex - 1 来工作,即 endIndex 是独占的,而 startIndex 是包含的。 您可以通过声明 endIndex = sentence.length() 并从 i = sentence.length()-1 迭代到 0 来修复它。

这样代码将是:

public static void main(String[] args) {

    String sentence = new String("pay no attention to that man behind the curtain");
    String reversed = "";

    int endIndex = sentence.length();
    for(int i = sentence.length()-1; i >= 0; i--) {
        if(sentence.charAt(i) == ' ') {
            reversed += sentence.substring(i+1, endIndex) + "\n";
            endIndex = i;
        }
    }
    reversed += sentence.substring(0, endIndex);
    System.out.println(reversed);
  }

更好的方法是:

a) 将字符串转换为字符数组

b) 然后将整个字符数组反转为:

niatruc eht dniheb nam taht ot noitnetta on yap

c) 然后原位反转每个空格之间的字母。

d) 你会得到新的字符数组,它表示:

curtain the behind man that to attention no pay

你可以从新的字符数组构造一个字符串。

【讨论】:

  • 有效!感谢您如此详细的回复并澄清我的错误。我对此很陌生,并且已经尝试了几个小时来找出我哪里出错了。
【解决方案2】:

试试这个代码:

import java.util.Scanner;
 
public class ReverseString
{
 public static void main(String[] args)
 {
 System.out.println("Enter string to reverse:");
 
 Scanner read = new Scanner(System.in);
 String str = read.nextLine();
 String reverse = "";
 
 
 for(int i = str.length() - 1; i >= 0; i--)
 {
 reverse = reverse + str.charAt(i);
 }
 
 System.out.println("Reversed string is:");
 System.out.println(reverse);
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多