在不改变位置的情况下反转字符串的每个单词(不使用内置功能)

时间:2015-12-02 06:07:23

标签: java string

我想用不同的注意事项(不是整个字符串,只是每个单词)来反转Java中String的每个单词。

示例1:如果输入字符串是“这是一个测试”,那么输出应该是“sihT si a tset”。

示例2:如果输入字符串是“这是一个测试”,那么输出应该是“sihT si a tset”。 [当某些词之间有多个空格时]

请提供理解算法

到目前为止我尝试了什么

class reverseAString
    {
        public static void main(String args[])
        {
        String str= "Test the product";
        String strArr[]= str.split(" ");


        for(int i=0;i<=strArr.length-1;i++)
        {
            for(int j=strArr[i].length()-1; j>=0;j--)
            {
                System.out.print(strArr[i].charAt(j));

            }
            System.out.printf(" ");
        }
        }
    }

---------

 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;
}

3 个答案:

答案 0 :(得分:0)

这种方法更为简洁。

class StringRev{
    public static void main(String args[]){
    String str[] = "Test the product".split(" ");
    String finalStr="";
        for(int i = str.length-1; i>= 0 ;i--){
            finalStr += str[i]+" ";
        }
        System.out.println(finalStr);
    }
}

答案 1 :(得分:0)

public static void main(String arg[]) {
    System.out.println(reverseWords("This is a test"));
}

// function to reverse each word
public static String reverseWords(String input) {
    String result = null;
    StringBuffer strBuffer = new StringBuffer();
    String split[] = input.split(" ");
    for (String temp : split) {
        if (temp != " ") {
            strBuffer.append(reverse(temp));
            strBuffer.append(" ");
        } else {
            strBuffer.append(" ");
        }
    }

    result = strBuffer.toString();
    return result;
}

// function to reverse individual word
public static String reverse(String input) {
    StringBuffer strBuffer = new StringBuffer();
    char[] charArray = input.toCharArray();
    for (int j = charArray.length - 1; j >= 0; j--) {
        strBuffer.append(charArray[j]);
    }
    return strBuffer.toString();
}
  • 基于空格拆分完整字符串
  • 然后将每个字符串转换为字符数组并反转 个别词。

答案 2 :(得分:-1)

自从我接触Java以来​​已经很长时间了,但这是算法。

String stringToReverse = "This is a Test";
String finalString = "";
Stack word = new Stack;
for(int i = 0; i < stringToReverse.length; i++){
    char chr = stringToReverse[i];
    if(chr == " " || i == (stringToReverse.length - 1)){
        while(word.count > 0){
            finalString += word.pop();
        }
         finalString += chr;
    }else{
        word.push(chr);
    }
}
相关问题