2012-03-16 43 views
0
final String message = 
         "Please enter the following code in the password reset screen:\n" + 
           "\n"+ 
           "{CODE} (((((" + codeStr + ")))))\n" + 
           "If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it." 
           .replace("{CODE}", codeStr); 

這導致很簡單的字符串替換失敗

請輸入密碼重置屏幕下面的代碼:{CODE}(((((5RE2GT4FWH)))))如果你沒有請求這個代碼,或者不知道這封電子郵件是關於什麼的,你可以放心地忽略它。

這樣一個簡單的替換如何不能工作?我認爲可能問題是{CODE}的兩個實例看起來很相似,但實際上是由不同的字符組成的,但我將其中一個複製粘貼到另一個上面,並沒有修復它。

回答

2

你只是在最後String對象調用replace()"If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it."]。

將它[最終String,在replace()之前]存儲到某個臨時變量並重試或使用括號。

6

問的是知道:

final String message = 
        (
          "Please enter the following code in the password reset screen:\n" + 
          "\n"+ 
          "{CODE}" + codeStr + "\n" + 
          "If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it." 
        ) 
        .replace("{CODE}", codeStr); 

由於缺乏圓括號,更換所所構成的字符串的最後一部分進行第一,然後纔是人連接到一起的部件。

+1

我只是喜歡你如何成功地回答自己的問題,現在大家都在給你免費upvotes;) – jzworkman 2012-03-16 15:41:40

2

你需要調用替換上滿弦:

final String message = 
     ("Please enter the following code in the password reset screen:\n" + 
     "\n"+ "{CODE} (((((" + codeStr + ")))))\n" + 
     "If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it." 
     ).replace("{CODE}", codeStr); 
0

您只在最後上打電話replace()字符串文字。您需要括號整個郵件周圍,像這樣:

final String message = 
    ("Please enter the following code in the password reset screen:\n" + 
    "\n"+ 
    "{CODE} (((((" + codeStr + ")))))\n" + 
    "If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it." 
    ) 
    .replace("{CODE}", codeStr); 
+1

我打電話ŧ他是一個平局,並且爲每個人都高歌猛進 – Bohemian 2012-03-16 15:36:49

0

這是使用了一種解決方案,將來自升級此以前的Java代碼風格受益於一個(舊的,但比這更新)java.util.Formatter

final String message = 
         "Please enter the following code in the password reset screen:\n" + 
           "\n"+ 
           "{CODE} (((((" + codeStr + ")))))\n" + 
           "If you didn't ask for this code, or don't know what this e-mail is about, you can safely ignore it." 
           .replace("{CODE}", codeStr); 

隨後將成爲

Formatter formatter = new Formatter(new StringBuilder, Locale.US); 
final String message = formatter.format("Please enter the following code in the password reset screen:\n\n %s (((((%s)))))\n", codeStr);