加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在Java中用Word反向字符串

发布时间:2020-12-15 02:49:17 所属栏目:Java 来源:网络整理
导读:我有以下代码逐字反转字符串,但我有一个问题,首先可以有人指出如何使它更好的代码?第二,如何在新字符串的开头删除我最终得到的空格. String str = "hello brave new world";tStr.reverseWordByWord(str)public String reverseWordByWord(String str){ int s
我有以下代码逐字反转字符串,但我有一个问题,首先可以有人指出如何使它更好的代码?第二,如何在新字符串的开头删除我最终得到的空格.
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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读