StringBuffer追加空格(“”)改为追加“null”

时间:2012-07-17 22:02:55

标签: java android

基本上我要做的就是取一个String,并替换里面的字母表中的每个字母,但是保留任何空格而不是将它们转换为“null”字符串,这是我打开这个问题的主要原因

如果我使用下面的函数并传递字符串“a b”,而不是获得“ALPHA BETA”,我会得到“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;
}

6 个答案:

答案 0 :(得分: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>

答案 1 :(得分:2)

如果字符串相等,则

String.compareTo()返回0,而不是1.读取它here

请注意,对于这种情况,您不需要将char转换为字符串,您可以执行

if(c == ' ') 

答案 2 :(得分:1)

使用

 Character.isWhitespace(c)  

解决了这个问题。最佳实践。

答案 3 :(得分:0)

首先,在这个例子中,s是什么?遵循代码很难。然后,你的compareTo似乎关闭了:

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

应该是

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

因为0表示“相等”(compareTo上为read up

答案 4 :(得分: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) {

中的条件错误

答案 5 :(得分:0)

如果源字符串在测试字符串之前,则String的compareTo方法返回-1,如果相等则返回0,如果源字符串如下则返回1。您的代码检查为1,它应该检查为0.