基本上我想要做的是採取一個字符串,並替換字母裏面的每個字母,但保留任何空格,而不是將它們轉換爲「空」字符串,這是我打開這個問題的主要原因。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;
}
如果對象相等,compareTo將返回0 – 2012-07-17 22:05:45
Character.isWhitespace(c)是您可以使用的。 – 2012-07-17 22:12:39
請不要在使用StringBuilder時使用StringBuffer。 – 2012-08-13 07:54:07