我正在尝试逐字反转字符串中的单词。但是我遇到了一些麻烦。我知道很多人都使用 StringBuilder
来解决这个问题,但我想在没有它的情况下尝试一下。
输入:
Hi there
输出:
iH ereht
目前,我的输入字符串停在最后一个单词处。我认为这是因为在我的代码中,代码的反转部分仅在检测到 ' '
或空格时反转。当也到达字符串的末尾时,我通过执行反向部分来更改此设置。 (i == len
) 然而这似乎并不能解决问题。我假设我的 if
、else 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/