我正在研究一个简单的子手程序。我的大部分代码都在工作,但是我很难弄清楚如何在char数组中获取多个匹配char的索引。例如,我有一个单词“ sushi”转换为char数组。如果用户猜测为“ s”,则应显示char数组中的所有“ s”。我的代码的方式是,实际上我有两个相同长度的char数组。第一个数组包含要猜测的单词的字符,而第二个数组包含问号。我的代码应遍历第一个数组并返回每个数组的索引匹配用户猜测的数组中的元素。然后,代码在每个指定的索引处插入用户猜测,并为用户显示第二个数组。不幸的是,在第二个数组中只有第一次出现发生了更改,因此匹配查询仅返回第一个索引。有问题的代码如下:
//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);
}
尝试Regex.Matches
构建正则表达式,并找到所有匹配项及其位置。
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = "a*";
string input = "abaabb";
foreach (Match m in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at index {1}.",
m.Value, m.Index);
}
}
// The example displays the following output:
// 'a' found at index 0.
// '' found at index 1.
// 'aa' found at index 2.
// '' found at index 4.
// '' found at index 5.
// '' found at index 6.`
http://msdn.microsoft.com/zh-CN/library/system.text.regularexpressions.regex.matches(v=vs.110).aspx
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句