在Java中用Word反向字符串 [英] Reverse String Word by Word in Java

查看:154
本文介绍了在Java中用Word反向字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code to reverse a string word by word, I have a question though, first could anyone point at how to make it better code? and second, how can I remove the space that I end up with at the beginning of the new string.

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

olleh evarb wen dlrow

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

notice the space at the beginning of the new string.

推荐答案

不使用split函数代码如下:

Not using the split function the code would look like:

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中用Word反向字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆