2015-01-31 43 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...