2015-01-31 44 views
0

只需刷新一些旧的java技术。目前正在解决一系列问题,并且这个问题将压缩字符串,格式为aabbcccDDDDeff到a2b2c3d4e1f2。我的代码中发生了一些奇怪的事情,请帮助对其进行分类:将字符串压缩成a2b3 ...等

public static void main(String[] args) { 
    String c = "aabbCCCCCdfff"; 
    System.out.println(compress(c)); 
} 

public static String compress(String s) { 
    String ns = ""; 
    int count = 0; 
    char temp = 0; 

    for (int x = 0; x < s.length(); x++) { 
     if (x == 0) { 
      ns.concat(String.valueOf(s.charAt(x)));  
      temp = s.charAt(x); 
      count++; 
     } else if (temp == s.charAt(x)) { 
      count++; 
     } else { 
      ns.concat(String.valueOf(count)); 
      count = 0; 
      ns.concat(String.valueOf(s.charAt(x))); 
      temp = s.charAt(x); 
     } 
    } 
    return ns; 
} 

输出显示为空。我想继续我的同样的逻辑

回答

1

String.concatString#concat docs)不会发生变异的字符串,它返回你需要分配给您的字符串变量

ns = ns.concat(theOtherString); 

,而不是这个新的字符串(本质上是一个无操作)

ns.concat(theOtherString); 

例如:

ns = ns.concat(String.valueOf(s.charAt(x))); 

我建议使用StringBuilder及其append方法进行多个字符串连接。如果您选择不这样做,那么如果您可以争论为什么性能优势不存在,或存在但不适用于您的用例,那么这很好。

+0

完美。哈哈。非常感谢!代码仍然搞砸了一点,但这是我需要的 – erp 2015-01-31 18:42:14

0

String在Java中是不可变的。 String.concat不会更改它被调用的String,它将返回一个新的String,它是要调用的对象和参数的连接。如果你想积累字符串,你会更好地使用StringBuilder

StringBuilder ns = new StringBuilder(); 
int count = 0; 
char temp = 0; 

for (int x = 0; x < s.length(); x++) { 
    if (x == 0) { 
     ns.append(s.charAt(x));  
     temp = s.charAt(x); 
     count++; 
    // rest of code...