gpt4 book ai didi

java - 在 Java 中逐字反转字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:39:15 26 4
gpt4 key购买 nike

我有以下代码逐字反转字符串,但我有一个问题,首先有人能指出如何使它更好的代码吗?其次,如何删除新字符串开头的空格。

String str = "hello brave new world";
tStr.reverseWordByWord(str)

public String reverseWordByWord(String str){
int strLeng = str.length()-1;
String reverse = "", temp = "";

for(int i = 0; i <= strLeng; i++){
temp += str.charAt(i);
if((str.charAt(i) == ' ') || (i == strLeng)){
for(int j = temp.length()-1; j >= 0; j--){
reverse += temp.charAt(j);
if((j == 0) && (i != strLeng))
reverse += " ";
}
temp = "";
}
}

return reverse;
}

此刻的短语变成:

olleh evarb wen dlrow

注意新字符串开头的空格。

最佳答案

不使用 split 函数的代码如下所示:

public static void reverseSentance(String str) {
StringBuilder revStr = new StringBuilder("");
int end = str.length(); // substring takes the end index -1
int counter = str.length()-1;
for (int i = str.length()-1; i >= 0; i--) {
if (str.charAt(i) == ' ' || i == 0) {
if (i != 0) {
revStr.append(str.substring(i+1, end));
revStr.append(" ");
}
else {
revStr.append(str.substring(i,end));
}
end = counter;
}
counter--;
}
System.out.println(revStr);
}

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com