问题:请写一个方法,两个参数,来判断第二个参数在第一个参数中出现了几次
1)用正则表达式,非常容易得出结果:
static int
FindCountInStringByRegex(string str, string pattern)
{
if (string.IsNullOrEmpty(str) ||
string.IsNullOrEmpty(pattern)) {
return 0;
}
if (pattern.Length > str.Length) {
return 0;
}
return
Regex.Matches(str, pattern).Count;
}
很简洁,但问题是,若str为"aaaa"、pattern为"aa",上面的方法结果为2,而实际要得到的应该是3。 这个用正则表达式还真就不知道怎么实现了。
2)无奈还是用最基本的方法实现吧:
static int
FindCountInString(string str, string pattern)
{
if (string.IsNullOrEmpty(str) ||
string.IsNullOrEmpty(pattern)) {
return 0;
}
if (pattern.Length > str.Length) {
return 0;
}
int count = 0, index = 0;
while (index < str.Length) {
index =
str.IndexOf(pattern, index);
if (index >= 0) count++;
else break;
index++;
}
return count;
}
posted on 2010-09-20 20:24
山伟 阅读(17)
评论(0) 编辑 收藏