posts - 21,  comments - 60,  trackbacks - 3

问题:请写一个方法,两个参数,来判断第二个参数在第一个参数中出现了几次

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) 编辑 收藏
<2010年9月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

昵称:山伟
园龄:6年10个月
粉丝:0
关注:0

搜索

 
 

常用链接

随笔分类(19)

随笔档案(21)

最新评论

阅读排行榜

评论排行榜

推荐排行榜