2013-04-11 21 views
0
String output = new String(encryptText); 
output = output.replaceAll("\\s", ""); 
return output; 

replaceAll("\\s", "");不起作用在java中,當使用空格將char數組轉換爲String時如何刪除該S​​tring中的空格?

+1

你的代碼似乎很好。它應該工作。我會檢查什麼encryptText看起來像 – gefei 2013-04-11 07:35:47

+0

可以請你分享輸入字符串?因爲str.replaceAll(「\\ s」,「」);應該管用。你也可以嘗試str.replaceAll(「」,「」); – 2013-04-11 07:36:02

+0

你應該添加你得到的錯誤或者爲什麼你發佈的解決方案不起作用或者你的問題似乎是這個問題的重複的一個例子:http://stackoverflow.com/questions/5455794/removing-whitespace-from -strings-in-java – 2013-04-11 07:36:09

回答

1
String output = new String(encryptText); 
output = output.replaceAll(" ", ""); 
return output; 
+0

我們不得不說這個解決方案僅適用於「純」空白字符。它不會捕獲像tab(\ t)這樣的「特殊」空白字符。相反,基於java.util.regex.Pattern:replaceAll(「\\ s」,「」)的解決方案適用於每個空格字符:[\ t \ n \ x0B \ f \ r] – 2013-04-11 08:24:22

0

您的代碼正常工作對我來說,看到here

反正你可以從spring framework使用StringUtils.trimAllWhitespace

output = StringUtils.trimAllWhitespace(output); 
+0

據我所知,該功能不是來自JDK。它來與春天? – 2013-04-11 07:37:23

+0

它說方法trimAllWhitespace(字符串)是未定義的類型 – sdfasdfw 2013-04-11 07:39:46

+0

java.lang不包含稱爲StringUtils的類。有幾個第三方庫,比如Apache Commons Lang或Spring框架。 爲了使用它,您需要在項目類路徑中輸入相關的jar並導入正確的類。 – 2013-04-11 07:40:39

0

你可以使用非正則表達式版本替換做這項工作:

output = output.replace(" ", ""); 
0

使用String.replaceAll(" ","")或者如果你想自己做,而沒有lib調用,使用這個。

 String encryptedString = "The quick brown fox "; 
     char[] charArray = encryptedString.toCharArray(); 
     char [] copy = new char[charArray.length]; 
     int counter = 0; 
     for (char c : charArray) 
     { 
      if(c != ' ') 
      { 
       copy[counter] = c; 
       counter++; 
      } 
     } 
     char[] result = Arrays.copyOf(copy, counter); 
     System.out.println(new String(result)); 
1

我面臨同樣的問題,然後我搜索很多,結果發現,它不是空格字符,但其被轉化成從字符數組字符串空值。這解決了我的問題 -

output.replaceAll(String.valueOf((char) 0), ""); 
相關問題