简体   繁体   English

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

[英]Count the string by words not char

I am working on this code in which it can identify the word listed below from the Web Browser. 我正在处理此代码,在其中可以从Web浏览器识别下面列出的单词。 Those words will turn into asterisk once they are identified and will count how many words were replaced but it didn't work. 一旦识别出这些单词,它们就会变成星号,并且会计算替换了多少个单词,但是没有用。 Someone can help? 有人可以帮忙吗?

Here is my code: 这是我的代码:

   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 = @"

select Word from ListWords "; 从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();
    }

Just count them before you replace them 在更换它们之前先数一下

Given 特定

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;
}

Example

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM