2014-12-02 86 views
0

我正在研究一個猜字遊戲的程序,並使用數組列表中的單詞列表。我正在通過一種方法,用戶將輸入一個字符來猜測它是否在單詞中。之後,程序會告訴用戶該字符出現在單詞中「x」個位置(以*****的形式顯示給用戶)。現在我想用給定位置的字符替換「*****」。我知道程序必須掃描單詞以及該字符所在的位置,它將用字符替換「*」。我怎麼做?到目前爲止,這是所有我對這個方法...如何用某個字母替換某個特定位置的字符

private static String modifyGuess(char inChar, String word,String currentGuess){ 
    int i = 0; 
    String str = " "; 
    while (i < word.length()){ 
     if(inChar == word.charAt(i)){ 

     } 
     else{ 
      i++; 
     } 
    } 
    return 
} 
+2

使用'StringBuilder' – khelwood 2014-12-02 22:55:52

回答

1

您可以使用此:

public String replace(String str, int index, char replace){  
    if(str==null){ 
     return str; 
    }else if(index<0 || index>=str.length()){ 
     return str; 
    } 
    char[] chars = str.toCharArray(); 
    chars[index] = replace; 
    return String.valueOf(chars);  
} 

或者你可以使用StringBuilder的方法

public static void replaceAll(StringBuilder builder, String from, String to) 
{ 
    int index = builder.indexOf(from); 
    while (index != -1) 
    { 
     builder.replace(index, index + from.length(), to); 
     index += to.length(); // Move to the end of the replacement 
     index = builder.indexOf(from, index); 
    } 
} 
2
private static String modifyGuess(char inChar, String word, String currentGuess) { 
    int i = 0; 
    // I assume word is the original word; currentGuess is "********" 
    StringBuilder sb = new StringBuilder(currentGuess); 
    while (i < word.length()) { 
     if (inChar == word.charAt(i)) { 
      sb.setCharAt(i, inChar); 
     } 
     i++; // you should not put this line in the else part; otherwise it is an infinite loop 
    } 

    return sb.toString(); 
} 
相關問題