2013-07-25 103 views
0

我正在做一个简单的hang子手游戏。除了用户输入正确字符的部分以外,我已经完成了所有工作,解决方案中的相应字符应替换为前者。在位置x处替换字符串中的单个字符

首先,这里是我的代码:

private void checkIfLetterIsInWord(char letter) 
{ 
    if (currentWord != string.Empty) 
    { 
     if (this.currentWord.Contains(letter)) 
     { 
      List<int> indices = new List<int>(); 
      for (int x = 0; x < currentWord.Length; x++) 
      { 
       if (currentWord[x] == letter) 
       { 
        indices.Add(x); 
       } 
      } 
      this.enteredRightLetter(letter, indices); 
     } 
     else 
     { 
      this.enteredWrongLetter(); 
     } 
    } 
} 


private void enteredRightLetter(char letter, List<int> indices) 
{ 
    foreach (int i in indices) 
    { 
     string temp = lblWord.Text; 
     temp[i] = letter; 
     lblWord.Text = temp; 

    } 
} 

所以我的问题是该行

temp[i] = letter; 

我来到这里的错误,指出“属性或索引不能被分配到 - 它是只读只要”。我已经搜索了一下,发现在运行时不能修改字符串。但我不知道如何替换包含猜测的标签。标签的格式是

_ _ _ _ _ _ _ //single char + space 

任何人都可以给我一个提示,我可以如何用猜测的字符替换解决方案中的字符?

回答

2

字符串是不可改变类,所以使用StringBuilder的代替

... 
     StringBuilder temp = new StringBuilder(lblWord.Text); 
     temp[i] = letter; // <- It is possible here 
     lblWord.Text = temp.ToString(); 
    ... 
+0

非常感谢,它的工作方式。有没有任何理由为什么字符串是不可改变的? – LeonidasFett

+1

字符串不可变的一些原因是:线程安全性,积极的编译器优化和内存保存(例如快速复制),副作用预防(例如字典) –

1

将字符串一个字符阵列String.ToCharArray()中,进行改变和将其转换回用字符串“新的字符串(CHAR [])”

2

StringBuilder解决方案是好的,但我认为这是矫枉过正。您可以改为使用toCharArray()。你也不需要更新标签直到循环结束。

private void enteredRightLetter(char letter, List<int> indices) 
{ 
    char[] temp = lblWord.Text.ToCharArray(); 
    foreach (int i in indices) 
    { 
     temp[i] = letter; 
    } 
    lblWord.Text= new string(temp); 
}