用单词而不是字符来计算字符串

时间:2018-09-08 02:27:07

标签: c# string count webbrowser-control

我正在研究此代码,它可以从Web浏览器中识别下面列出的单词。一旦识别出这些单词,它们就会变成星号,并且会计算替换了多少个单词,但是没有用。有人可以帮忙吗?

这是我的代码:

   private void button1_Click(object sender, EventArgs e)
    {
        webBrowser1.Navigate(txbAdress.Text);
        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
    }

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        IHTMLDocument2 doc2 = webBrowser1.Document.DomDocument as IHTMLDocument2;
        StringBuilder html = new StringBuilder(doc2.body.outerHTML);


        string query;
        query = @"

从ListWords中选择单词 “;

        List<string> words = new List<string>();

        DataSet ds;
        DataRow drow;

        ds = DatabaseConnection.Connection1(query);
        int index, total;

        total = ds.Tables[0].Rows.Count;

        string current_word;

        for (index = 0; index < total; index++ )
        {
            drow = ds.Tables[0].Rows[index];
            current_word = drow.ItemArray.GetValue(0).ToString();

            words.Add(current_word);
        }

        Console.WriteLine(query);


        Console.WriteLine("array:" + words);
        foreach (String key in words)
        {
           // String substitution = "<span style='background-color: rgb(255, 0, 0);'>" + key + "</span>";

            int len = key.Length;
            string replace = "";

            for ( index = 0; index < len; index++)
            {
                replace += "*";
            }

            html.Replace(key, replace);
            //count++;
        }

        //Console.WriteLine("Total number of words: " + count);


        doc2.body.innerHTML = html.ToString();
    }

1 个答案:

答案 0 :(得分:1)

只需数一数,然后再更换

给予

public int CountOccurrences(string source, string match)
{
   var pos = 0;
   var count = 0;
   while ((pos < source.Length) && (pos = source.IndexOf(match, pos, StringComparison.Ordinal)) != -1)
   {
      count++;
      pos += match.Length;
   }

   return count;
}

示例

var count = CountOccurrences(html,key);
html.Replace(key, substitution);