C#计算字符串中子字符串出现的次数

2009年4月14日星期二

C#计算字符串中子字符串出现的次数

计算字符串中子字符串出现的次数时,首先定义一个int类型的变量,并将其初始值设为0,该变量用来记录子字符串出现的次数;然后利用richTextBox类的Find方法查找指定的子字符串,每当找到一个与指定子字符串相匹配的项时,定义的变量值就加1,依此累推,直到找不到指定子字符串为止。计算字符串中子字符串出现次数的关键代码如下:





while (M_int_index != -1)
{
     M_int_start = 0;
     M_int_end = richTextBox1.Text.Trim().Length;
     M_int_index = richTextBox1.Find(this.textBox1.Text.Trim(), M_int_start, M_int_end, RichTextBoxFinds.None);
     if (M_int_index == -1)
     {
          MessageBox.Show("字符串" + this.textBox1.Text + "一共出现了" + P_int_num.ToString() + "次。", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
          M_int_index = 0;
          while (M_int_index != -1)
          {
              M_int_start = 0;
              M_int_end = richTextBox1.Text.Trim().Length;
              M_int_index = richTextBox1.Find("计数", M_int_start, M_int_end, RichTextBoxFinds.None);
              if (M_int_index != -1)
              {
                  richTextBox1.SelectedText = this.textBox1.Text.Trim();
                  M_int_index += this.textBox1.Text.Length;
              }
           }
      }
      else
      {
          richTextBox1.SelectedText = "计数";
          M_int_index += this.textBox1.Text.Length;
          P_int_num += 1;
       }
 }





vb.net的代码如下

Dim regex As Regex
Dim count as Integer
regex = New Regex("abc")
count=regex.Matches("abcabcabcabc", "abc").Count()



using System.Text.RegularExpressions;

string s = @"a\w";
string s2 = @"defa\wdfdfsdfa\wddfdsaw";

Regex re = new Regex(Regex.Escape(s), RegexOptions.IgnoreCase|RegexOptions.Singleline);
MatchCollection mc = re.Matches(s2);
Console.WriteLine(mc.Count);

    0 评论:

    发表评论