读书人

matchCollection遍历的困惑

发布时间: 2012-12-23 11:28:15 作者: rapoo

matchCollection遍历的疑惑!


可是呢,用for循环的话

            for (int i = 0; i < matches.Count; i++)
{
arr[0, i] = m.Index;
arr[1, i] = m.Index + m.Length;
}

很明显matchCollection里面的match对象无法单独搞出来使用,如上面的m.Index,m应该是match对象,可是for循环遍历不出match对象。用foreach遍历的话如下:
            foreach (Match m in Matches)
{
arr[0, i] = m.Index;
arr[1, i] = m.Index + m.Length;
}

我想要i++,可是foreach里面弄不出自增的数,也就是说这个数组不能自动往下遍历存储所有的匹配结果(match
)的起始和结束位置的数值,我该怎么办,谢谢,!!
[最优解释]
直接这样写就行了:
string s = "你好,请问这个要怎么做呢?谢谢了,非常感谢!";
MatchCollection matches = Regex.Matches(s, @"谢");
int[,] arr = new int[2, matches.Count];
for (int i = 0; i < matches.Count; i++)
{
arr[0, i] = matches[i].Index;
arr[1, i] = matches[i].Index + matches[i].Length;
}
//以下是输出:
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
Console.Write(arr[i, j] + " ");
Console.WriteLine();
}

[其他解释]
Match[] marr = matches.OfType<Match>().ToArray();

也可以。
[其他解释]
Match[] marr = matches.Cast<Match>().ToArray();
for (int i = 0; i < marr.Count(); i++)
{
arr[0, i] = marr[i].Index;
arr[1, i] = marr[i].Index + marr[i].Length;
}
[其他解释]
你好,那个CAST 是怎么回事啊??看了msdn没看懂谢谢阿
[其他解释]
dalmeeme 说的对阿,这个我真忘记了可以用下标指名单个元素,devmiao得我没看懂,能讲讲吗
[其他解释]
msdn上有,linq操作符。

读书人网 >C#

热点推荐