2016-11-10 78 views
-3

我需要幫助完成此代碼。我正在嘗試閱讀單詞中的每個字母,並用replaceLetter更改letterToReplace。問題是,我不能使用.replace如何替換字符串中的字母而不使用.replace在Java中

請幫

public String replaceLetter(String word, char letterToReplace, char replacingLetter) 
{ 
    String ans = ""; 
    for(int i = 0; i < word.length(); i++) 
    { 
     char current = word.charAt(i); 
     if(current == letterToReplace) 
     { 
      letterToReplace = replacingLetter; 
     } 
     ans += Character.toString(word.charAt(i)); 
    } 
    return ans; 
} 

回答

1

你幾乎沒有。你只需要更新和打印current

if(current == letterToReplace) 
{ 
    current = replacingLetter; 
} 
ans += Character.toString(current); 
+0

感謝您的迴應!但我不太明白......通過更新電流,你的意思是什麼? –

+0

@JonahLavi我展示了我的意思。 – shmosel

+0

哦,對不起,我沒有看到有什麼不同。謝謝! –

相關問題