2009-02-01 40 views
5

我試圖製作一種以相反順序返回單詞串的方法。返回在Java中輸入爲反向文本的字符串

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()

+0

你的意思是,你必須使用只內置了Java類? – ecleel 2009-02-01 21:21:07

回答

8

在Java中,字符串是不可變的,即它們不能被改變。 concat()用串聯返回一個新的字符串。所以,你想是這樣的:

stringOut = stringOut.concat(word); 

stringOut += word 

爲雷筆記,還有更簡潔的方式,雖然做到這一點。

0

那是因爲你需要CONCAT返回分配到的東西:在Java中

stringOut=stringOut.concat(word) 

字符串(和.net)是不可改變的。

1

如果您使用String類的indexOf方法而不是該循環來查找每個空間,那麼您會做得更好。

-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循環後一次。

希望這會有所幫助!

2
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(應該處理字符串時,被允許...)

+0

不錯,但應該是「return reversed.trim();」或者爲第一次迭代添加一些規則,因爲您在末尾添加了空白字符。 – 2011-02-25 09:05:28

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