2016-01-10 26 views
0

我試圖在特定位置替換字符串中的字母。我知道有很多這樣的問題,但我仍然陷入困境。例如:(java)在遊戲循環中替換字符串中的一個特定字符的所有實例

例如:hiddenWord =「----」 從我的循環中我發現在位置1和3我想用「a」替換「 - 」。所以那hiddenWord now =「-a-a」。

主要剪斷:

 btnA = new JButton("A"); 
    btnA.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      count += 1; 
      lblTries.setText(count + " Tries"); 
      int i; 
      String newName=""; 
      if (wordList[num].indexOf('a') > 0){ 
       System.out.print("Has A: "); 
       for (i = -1; (i = wordList[num].indexOf("a", i + 1)) != -1;) { 
        //System.out.print(i + " ,"); 

        newName = hiddenWord.substring(0,i)+'a'+hiddenWord.substring(5); 
       }     
      } 
      System.out.println(newName); 
     } 
    }); 

請讓我知道,如果有任何其他的約定,我應該做的differently..as你能告訴我是很新的這一點。

編輯:

someone_somewhere幫助我看到了我的錯誤。我的新代碼看起來其次

   if (wordList[num].indexOf('a') >= 0){ 
       for (int i = -1; (i = wordList[num].indexOf("a", i + 1)) != -1;) { 
        hiddenWord = putCharAtPlaces(hiddenWord,'a',new int[]{i}); 
        lblWordDisplay.setText(hiddenWord); 
        System.out.println(i); 
       } 
+1

的可能的複製(http://stackoverflow.com/questions/6952363/replace- a-character-at-a-specific-index-in-a-string) – Tom

回答

0

嘗試是這樣的:

public static void main(String args[]){ 
     String word = "----------"; 
     word = putCharAtPlaces(word,'a',new int[]{0,2,3}); 
     System.out.println(word); 
    } 

    private static String putCharAtPlaces(String word,char c, int[] is) { 
     StringBuilder stringBuilder = new StringBuilder(word); 
     for(int place:is){ 
      stringBuilder.setCharAt(place, c); 
     } 
     return stringBuilder.toString(); 
    } 

你把字符設置btnK下。 關於第一個字符不工作冷杉您btnJ應該是:?在字符串中的特定索引替換字符]

btnJ.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     count += 1; 
     lblTries.setText(count + " Tries"); 
     if (wordList[num].indexOf('j') >= 0) {//notice this is >= 0 to get the first char to work 
      for (int i = -1; (i = wordList[num].indexOf("j", i + 1)) != -1;){ 
       hiddenWord = putCharAtPlaces(hiddenWord, 'j', 
         new int[] { i }); 
       lblWordDisplay.setText(hiddenWord); 
       System.out.println(i); 
      } 
     } 
    } 
}); 
+0

這在大部分情況下效果很好,但我仍然遇到問題!第一個字母不計算在內。我正在使用你的主要方法的修改版本,我試圖找出如何發佈我的新修改的代碼。 – Alex

+0

你應該可以編輯你的問題。因此,只需在現有問題末尾添加新代碼即可。像這樣,我不確定你遇到的問題是什麼。 –

+0

我在原始問題中添加了更多信息。感謝您花時間幫助我。 – Alex

0

你可以使用子,但更簡單的方法是使用StringBuilder

StringBuilder sb = new StringBuilder("----"); 

sb.setCharAt(1, 'a'); 
sb.setCharAt(3, 'a'); 

String s= sb.toString(); // -a-a 

我要再次設置StringBuilder的和不斷增加的信件給它。

相關問題