【发布时间】:2014-12-07 07:33:00
【问题描述】:
我正在开发一个简单的刽子手程序。我的大部分代码都在工作,但我无法弄清楚如何获取 char 数组中多个匹配字符的索引。例如,我将单词“sushi”转换为 char 数组。如果用户猜到一个“s”,那么应该显示 char 数组中的所有“s”。我的代码的方式是,我实际上有两个长度相同的 char 数组。第一个数组保存要猜测的单词的字符,而第二个数组保存问号。我的代码应该遍历第一个数组并返回数组中与用户猜测匹配的 each 元素的索引。然后,代码在每个指定索引处插入用户猜测,并为用户显示第二个数组。不幸的是,只有第一个出现在第二个数组中发生了变化,所以只有第一个索引从匹配查询中返回。有问题的代码如下:
//check if char array contains the user input
if (guessThis.Contains(Convert.ToChar(textBox1.Text)))
{
//save user input as char
char userGuess = Convert.ToChar(textBox1.Text);
//iterate through first char array
for (int i = 0; i < guessThis.Length - 1; i++ )
{
//check each element in the array
//probably don't need both for and foreach loops
foreach (char c in guessThis)
{
//get index of any element that contains the userinput
var getIndex = Array.IndexOf(guessThis, c);
//check if the element matches the user guess
if (c == userGuess)
{
//insert the userguess into the index
displayAnswer[getIndex] = userGuess;
}
}
}
//update the display label
answerLabel.Text = new string(displayAnswer);
已解决: 根据所选答案中的示例,我将代码更新为:
//check if char array contains the user input
if (guessThis.Contains(Convert.ToChar(textBox1.Text)))
{
//save user input as char
char userGuess = Convert.ToChar(textBox1.Text);
string maybeThis = textBox1.Text;
string tryThis = new string(guessThis);
foreach (Match m in Regex.Matches(tryThis, maybeThis))
{
displayAnswer[m.Index] = userGuess;
}
answerLabel.Text = new string(displayAnswer);
}
【问题讨论】:
标签: c# arrays visual-studio-2010 foreach indexing