2015-11-05 99 views
3

我有一個帶空格的字符串,我希望那個空格替換爲"\_" 。例如,這裏是我的代碼如何用java字符串中的「 _」替換空格?

String example = "Bill Gates"; 
example = example.replaceAll(" ","\\_");  

而例子的結果是:「Bill_Gates」而不是「Bill \ _Gates」。當我嘗試做這樣的

String example = "Bill Gates"; 
example = example.replaceAll(" ","\\\\_"); 

例子的結果是: 「比爾\\ _門」 不是 「比爾\ _Gates」

+0

相似問題:http://stackoverflow.com/questions/31298982/how-can-i-replace-with-in-java-string –

+1

使用replace,'example.replace(「」,「\\ _」 );' –

+0

@Leo你想要單個反斜槓? –

回答

1

嘗試:

String example = "Bill Gates"; 
example = example.replaceAll(" ","\\\\_"); 
System.out.println(example); 
+0

是的,這是正確的,我做對了,但認爲它是錯的。謝謝 – LeoPro

1
public static void main(String[] args) { 
     String example = "Bill Gates"; 
     example = example.replaceAll(" ", "\\\\_"); 
     System.out.println(example); 
    } 

輸出

Bill\_Gates 
+0

非常感謝Ankur,我做了調試,所以我沒有看到它是如何呈現的。在現場調試中,我看到了2個反斜槓,所以我認爲這是不正確的 – LeoPro

+0

@LeoPro請接受/ upvote答案 –

+0

對不起,我想投票,但我的聲望是不夠的:(現在只有10,我需要15投票給你們up – LeoPro

2

您需要使用replaceAll(" ","\\\\_")而不是replaceAll(" ","\\_")。因爲'\\'是一個文字。它將被編譯爲'\'單斜槓。當你通過這個方法replaceall。它將採用第一個斜槓作爲「_」的轉義字符。如果你看裏面0​​方法

while (cursor < replacement.length()) { 
     char nextChar = replacement.charAt(cursor); 
     if (nextChar == '\\') { 
      cursor++; 
      if (cursor == replacement.length()) 
       throw new IllegalArgumentException(
        "character to be escaped is missing"); 
      nextChar = replacement.charAt(cursor); 
      result.append(nextChar); 
      cursor++; 

當它找到一個單斜槓它將取代斜線的下一個字符。所以你必須輸入「\\\\ _」來替換方法。然後它將被處理爲「\\ _」。方法將看第一個斜槓並替換第二個斜槓。然後它將取代下劃線。

+0

感謝您的詳細解釋。我想爲您投票,但我的名聲還不夠 – LeoPro