2012-07-17 476 views
0

基本上我想要做的是採取一個字符串,並替換字母裏面的每個字母,但保留任何空格,而不是將它們轉換爲「空」字符串,這是我打開這個問題的主要原因。StringBuffer附加空格(「」)附加「空」而不是

如果我使用下面的函數,並傳遞而不是讓「α+β」字符串「A B」,我得到「ALPHAnullBETA」。

我已經試過檢查所有可能的方式,如果當前通過迭代個別字符是一個空間,但似乎沒有任何工作。所有這些場景都是假的,就好像它是一個普通字符一樣。

public String charConvert(String s) { 

    Map<String, String> t = new HashMap<String, String>(); // Associative array 
    t.put("a", "ALPHA"); 
    t.put("b", "BETA"); 
    t.put("c", "GAMA"); 
    // So on... 

    StringBuffer sb = new StringBuffer(0); 
    s = s.toLowerCase(); // This is my full string 

    for (int i = 0; i < s.length(); i++) { 
     char c = s.charAt(i); 

     String st = String.valueOf(c); 
     if (st.compareTo(" ") == 1) { 
      // This is the problematic condition 
      // The script should just append a space in this case, but nothing seems to invoke this scenario 
     } else { 
      sb.append(st); 
     } 

    } 

    s = sb.toString(); 

    return s; 
} 
+1

如果對象相等,compareTo將返回0 – 2012-07-17 22:05:45

+0

Character.isWhitespace(c)是您可以使用的。 – 2012-07-17 22:12:39

+0

請不要在使用StringBuilder時使用StringBuffer。 – 2012-08-13 07:54:07

回答

5

compareTo()將返回0,如果字符串相等。它返回第一個字符串的正數是「大於」第二個。

但實際上沒有必要爲比較字符串。你可以這樣做,而不是東西:

char c = s.charAt(i); 

if(c == ' ') { 
    // do something 
} else { 
    sb.append(c); 
} 

甚至爲你的使用情況較好:

String st = s.substring(i,i+1); 
if(t.contains(st)) { 
    sb.append(t.get(st)); 
} else { 
    sb.append(st); 
} 

爲了獲得更清潔的代碼,你的地圖應該從CharacterString,而不是<String,String>

2

String.compareTo()返回0,如果字符串相等,而不是1讀到它here

注意,對於這種情況下,你不需要爲char轉換爲字符串,你可以做

if(c == ' ') 
0

首先,所有的,什麼是在這個例子中s?很難遵循代碼。然後,你的compareTo似乎關:

if (st.compareTo(" ") == 1) 

應該

if (st.compareTo(" ") == 0) 

因爲0意味着 「平等」(read up上的compareTo)

0

從的compareTo文檔:The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal;

你有錯誤的條件if (st.compareTo(" ") == 1) {

0

如果源字符串在測試字符串之前返回-1,則返回-1,如果源字符串在後面,則返回1。你的代碼檢查1次,並應檢查0

1

使用

Character.isWhitespace(c) 

,解決了這個問題。最佳實踐。