微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何不使用数组,split或StringBuilder逐字地逆转字符串

如何解决如何不使用数组,split或StringBuilder逐字地逆转字符串

我正在尝试不使用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);
}

enter image description here

解决方法

尝试以下代码:

Route
,

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

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

如果要在新行中打印每个单词,可以将每个单词添加到单词列表中,然后在新行中打印每个单词,也可以在每个单词的末尾添加“ \ n”。

还要注意窗帘上的字母“ n”是如何丢失的,并且没有 最后两个词之间的空格。

这是因为Java中的endIndexsentence.length()-1开始,而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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。