java - 在字符串中逐字反转

标签 java string

我正在尝试逐字反转字符串中的单词。但是我遇到了一些麻烦。我知道很多人都使用 StringBuilder 来解决这个问题,但我想在没有它的情况下尝试一下。

输入:

Hi there

输出:

iH ereht

目前,我的输入字符串停在最后一个单词处。我认为这是因为在我的代码中,代码的反转部分仅在检测到 ' ' 或空格时反转。当也到达字符串的末尾时,我通过执行反向部分来更改此设置。 (i == len) 然而这似乎并不能解决问题。我假设我的 ifelse if 语句和 for loop 中也存在一些逻辑错误。我想知道是否有人可以指导我朝着正确的方向前进。

我一直在处理的测试用例字符串是

“您好,Doge 先生!”

我现在得到的输出是

iH ereht <-- 字符串末尾的空格。

我在代码执行过程中打印了一些文本,最后一个单词 (Mr.Doge!) 被存储到 temp 中,但它没有被反转。

这是我编译代码时的输出:

0
H
1
Hi
2
i
iH
3
t
4
th
5
the
6
ther
7
there
8
iH e
iH er
iH ere
iH ereh
iH ereht
9
M
10
Mr
11
Mr.
12
Mr.D
13
Mr.Do
14
Mr.Dog
15
Mr.Doge
16
Mr.Doge!
iH ereht 

我的代码:

public static String reverseWord(String str){
    int len = str.length();
    String reverse = "", temp = "";

    for (int i = 0; i < len; i++) {
        System.out.println(i);
        if (str.charAt(i) != ' '){
            temp += str.charAt(i);
            System.out.println(temp);
        }
        else if (str.charAt(i) == ' ' || i == len){
        //if (str.charAt(i) == ' ') {
            for (int j = temp.length() - 1; j >= 0; j--) {      // reverse
                reverse += temp.charAt(j);                      // append in reverse
                System.out.println(reverse);
            }
            reverse += ' ';
            temp = "";
        }
    }
    return reverse;
}

最佳答案

通过一些修改,这一定可以工作。查看代码中的注释,看看我修改了什么。

代码:

public static void main(String[] args)
{
    System.out.println(reverseWord("Hello world Liondancer"));
}

public static String reverseWord(String str)
{
    int len = str.length();
    String reverse = "", temp = "";

    for (int i = 0; i < len; i++) {   // i == len comparison is unuseful since 'i' won't never be 'len'
        if (str.charAt(i) != ' ') {
            temp = str.charAt(i) + temp; // What you did, but add the current character first, THIS IS THE REVERSE!!!
        } else if (str.charAt(i) == ' ') {
            reverse += temp + " ";
            temp = "";
        }
    }
    reverse += temp; // Added this outside the loop to add last word stored in 'temp'
    return reverse;
}

输出:

olleH dlrow recnadnoiL

注意:

我删除了嵌套的 for,因为它不是必需的。

关于java - 在字符串中逐字反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20943166/

相关文章:

c++ - 类中字符串成员变量的语法错误

c - 如何打印 char * a[] 的返回值?

java - EditText View 返回 null

java - 类型变量的泛型类型?

c# - 如何生成一个随机字符串,并指定你想要的长度,或者更好地生成你想要的规范的唯一字符串

c++ - 将字符串分配给 char 数组

javascript - 将 json 格式变量转换为 javascript 数组

java - 在 Android 上滚动 RecyclerView 时如何修复计时器?

java - 在 Java 中使用短路评估进行编程

java - 在Java接口(interface)实现中避免使用instanceof