【问题标题】:StringBuffer Append Space (" ") Appends "null" InsteadStringBuffer Append Space (" ") 改为追加“null”
【发布时间】:2012-07-17 22:02:55
【问题描述】:

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

如果我使用下面的函数并传递字符串“a b”,而不是得到“ALPHA BETA”,我得到的是“ALPHAnullBETA”。

我尝试了所有可能的方法来检查当前迭代的单个字符是否为空格,但似乎没有任何效果。所有这些场景都会给出 false ,就好像它是一个常规字符一样。

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
  • Character.isWhitespace(c) 是你可以使用的。
  • 可以使用StringBuilder时请不要使用StringBuffer。

标签: java android


【解决方案1】:

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

要获得更简洁的代码,您的 Map 应该从 CharacterString 而不是 &lt;String,String&gt;

【讨论】:

    【解决方案2】:

    String.compareTo() 如果字符串相等则返回 0,而不是 1。阅读它here

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

    if(c == ' ') 
    

    【讨论】:

      【解决方案3】:

      使用

       Character.isWhitespace(c)  
      

      解决问题。最佳实践。

      【讨论】:

        【解决方案4】:

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

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

        应该是

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

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

        【讨论】:

          【解决方案5】:

          来自 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) {你的条件有误

          【讨论】:

            【解决方案6】:

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

            【讨论】:

              猜你喜欢
              • 2015-03-28
              • 2011-04-28
              • 2015-08-03
              • 2016-05-21
              • 1970-01-01
              • 1970-01-01
              • 2016-08-17
              • 2014-10-23
              • 1970-01-01
              相关资源
              最近更新 更多