返回在Java中作为反向文本输入的字符串

时间:2009-02-01 21:14:18

标签: java string

我正在尝试创建一个以相反顺序返回单词字符串的方法。

IE /“西班牙的降雨主要落在”     会回归:“大部分时间都落在西班牙的雨中”

为此,我不应该使用任何内置的Java类,只需要基本的Java。

到目前为止,我有:

    lastSpace = stringIn.length(); 

    for (int i = stringIn.length() - 1; i >= 0; i--){
        chIn = stringIn.charAt(i);
        if (chIn == ' '){
            word = stringIn.substring(i + 1, lastSpace);
            stringOut.concat(word);
            lastS = i;
        }
    }
    word = stringIn.substring(0,lastSpace);
    stringOut.concat(word);

    return stringOut;

我的问题是当stringOut返回给它的调用者时,它总是一个空字符串。

我做错了吗?也许我使用string.concat()

6 个答案:

答案 0 :(得分:8)

在Java中,字符串是不可变的,即它们不能被更改。 concat()返回带有串联的新字符串。所以你想要这样的东西:

stringOut = stringOut.concat(word);

stringOut += word
Ray指出,虽然有更简洁的方法可以做到这一点。

答案 1 :(得分:3)

public String reverseWords(String words)
{
  if(words == null || words.isEmpty() || !words.contains(" "))
    return words;

  String reversed = "";
  for(String word : words.split(" "))
    reversed = word + " " + reversed;

  return reversed.trim();
}

只使用的API是String(操作字符串时应该允许...)

答案 2 :(得分:1)

如果使用String类的indexOf方法而不是该循环来查找每个空格,那么你会做得更好。

答案 3 :(得分:0)

那是因为你需要将concat的返回值指定为:

stringOut=stringOut.concat(word)

Java(和.net)中的字符串是不可变的。

答案 4 :(得分:0)

public String reverseString(String originalString)
     {
     String reverseString="";
     String substring[]=originalString.split(" ");// at least one space between this double                      //quotes

    for(int i=(substring.length-1);i>=0;i--)
        {
        reverseString = reverseString + substring[i];
        }

      return sreverseString;
     }

答案 5 :(得分:-2)

我觉得自己喜欢编码,所以你走了:


import java.util.*;

class ReverseBuffer {
    private StringBuilder soFar;
    public ReverseBuffer() {
        soFar = new StringBuilder();
    }

    public void add(char ch) {
        soFar.append(ch);
    }

    public String getReversedString() {
        String str = soFar.toString();
        soFar.setLength(0);
        return str;
    }
}

public class Reverso {
    public static String[] getReversedWords(String sentence) {
        ArrayList < String > strings = new ArrayList < String >();
        ReverseBuffer rb = new ReverseBuffer();
        for(int i = 0;i < sentence.length();i++) {
            char current = sentence.charAt(i);
            if(current == ' ') {
                strings.add(rb.getReversedString());
            }
            else {
                rb.add(current);
            }
        }
        strings.add(rb.getReversedString());
        Collections.reverse(strings);
        return (String[])strings.toArray(new String[0]);
    }

    public static void main(String[] args) {
        String cSentence = "The rain in Spain falls mostly on the";
        String words[] = Reverso.getReversedWords(cSentence);
        for(String word : words) {
            System.out.println(word);
        }
    }
}

编辑:在循环之后不得不再次调用getReversedString。

希望这有帮助!