在Java中用Word反向字符串
发布时间:2020-05-25 01:36:05 所属栏目:Java 来源:互联网
导读:我有以下代码逐字反转字符串,但我有一个问题,首先可以有人指出如何使它更好的代码?第二,如何在新字符串的开头删除我最终得到的空格. String str = hello brave new world;tStr.reverseWordByWord(str)public String reverseWordByWord(String str){ int strL
|
我有以下代码逐字反转字符串,但我有一个问题,首先可以有人指出如何使它更好的代码?第二,如何在新字符串的开头删除我最终得到的空格. 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;
}
此刻的短语变为:
注意新字符串开头的空格. 解决方法不使用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);
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
