2016-03-14 54 views
-2

我必須替換模式之間的文本。這裏是功能:替換文本之間的模式

public String replace(String text) { 
    String text = "My name is %NAME%."; 
    String pattern = "%NAME%"; 
    String textReplaced = ""; 
    "Here comes the code" 
    return textReplaced; 
} 

執行函數replace(「Darius」)的結果; 必須是這樣的字符串:「我的名字是大流士。」

我不能使用替換()replaceFirst(),這是一個條件。

執行此實現的最佳方法是什麼?

+1

爲什麼不能使用'replace'? – Reimeus

+4

'replace'不使用正則表達式。 –

+0

'replace()'不使用Regex,而是'replaceAll()'。 – user2004685

回答

2

我不能使用正則表達式替換。我不知道你爲什麼這麼想,但你可以簡單地用replace()來做。

這裏是代碼片段:

public String replace(String text) { 
    String text = "My name is %NAME%."; 
    String pattern = "%NAME%"; 
    String textReplaced = "Darius"; 

    String result = text.replace(pattern, textReplaced); 
    System.out.println(result); 
    return result; 
} 

輸出:

My name is Darius. 

另外,如果你不想使用replace()那麼你也可以做到以下幾點:

public String replace(String text) { 
    String text = "My name is %NAME%."; 
    String pattern = "%NAME%"; 
    String textReplaced = "Darius"; 

    String[] result = text.split(" "); 
    StringBuilder sb = new StringBuilder(); 
    for(int i = 0; i < result.length; i++) { 
     sb.append(result[i].contains(pattern) ? textReplaced + " " : result[i] + " "); 
    } 

    return sb.toString(); 
} 
+0

你不想返回結果'? –

+0

@安迪對不起,我的壞! :) – user2004685

+0

@MarioNavarroClaras請檢查更新的解決方案。 – user2004685

相關問題