在不同位置替换字符串中的多个字符

问题描述:

我正在用java编写一个“Hangman”游戏,而且我偶然发现了一个问题。在不同位置替换字符串中的多个字符

static String word = JOptionPane.showInputDialog(null, "Enter word"); 
static String star = ""; 
public static Integer word_length = word.length(); 
public static Integer nrOfAttempts = 12; 
public static Integer remainingAttempt = nrOfAttempts; 

public static void main(String[] args) { 
    // String görs med lika många stjärnor som ordet har tecken 
    for (int i = 0; i < word.length(); i++) { 
     star += "_"; 
    } 
    attempt(); 
} 

public static void attempt(){ 

    for(int o = 0; o < nrOfAttempts; o++) { 
     String attempt = JOptionPane.showInputDialog(null, "Enter first attempt"); 

     if (attempt.length() > 1) { 
      JOptionPane.showMessageDialog(null, "Length of attempt can only be one character long"); 
      attempt(); 

     } else { 

      if (word.contains(attempt)) { 
       int attemptIndex = word.indexOf(attempt); 
       star = star.substring(0,attemptIndex) + attempt + star.substring(attemptIndex+1); 


       JOptionPane.showMessageDialog(null, "Hit!\nThe word is now:\n"+star); 
       nrOfAttempts++; 

       if (star.equals(word)) { 
        JOptionPane.showMessageDialog(null, "You've won!"); 
        System.exit(0); 
       } 
      } else { 
       remainingAttempt--; 
       JOptionPane.showMessageDialog(null, "Character not present in chosen word\nRemaining Attempts: "+remainingAttempt); 
      } 
     } 
    } 
    JOptionPane.showMessageDialog(null, "Loser!"); 
} 

当我想要替换在特定的地方,特定字符的“明星”的字符串(包括下划线的字),只替换匹配的第一个字符。一遍又一遍,这样就不可能取胜。

因此,诸如“马铃薯”和“酷”等词语不起作用。

我想要它做的是取代所有匹配的字母,而不仅仅是它看到的第一个。有没有可能做到这一点,而不创建一个数组?

这里是你会怎么做信更换你的情况整个字符串:

int attemptIndex = word.indexOf(attempt); 
while (attemptIndex != -1) { 
    star = star.substring(0, attemptIndex) + attempt + star.substring(attemptIndex + 1); 
    attemptIndex = word.indexOf(attempt, attemptIndex + 1); 
} 

indexOf指数的第二个版本,开始从提供搜索。这是一个+1来避免再次找到同一封信。文档indexOf

请注意,使用字符数组StringBuilder可能是一个更有效的解决方案,因为它可以避免创建许多临时字符串。

要替换所有匹配的字母一步一步,你可以使用正则表达式replaceAll(String regex, String replacement)String doc
例子:

String word = "potato"; 
String start = "______"; 
String attempt = "o"; 

start = word.replaceAll("[^"+attempt+"]", "_"); 
// start = "_o___o"; 

attempt += "t"; 
start = word.replaceAll("[^"+attempt+"]", "_"); 
// start = "_ot_to"; 

attempt += "p"; 
start = word.replaceAll("[^"+attempt+"]", "_"); 
// start = "pot_to"; 

attempt += "a"; 
start = word.replaceAll("[^"+attempt+"]", "_"); 
// start = "potato"; -> win 
+0

的事情是,我想这个词来替换字符,其中仅下划线。要做到这一点,我必须使用索引(我认为) – tTim

+0

下划线是一个字符,所以你可以例如'''替换(尝试,'_')''' –

+0

是的,但然后所有的下划线将成为一个权利?在我的情况下,它会'替换(尝试,'_')' – tTim