【问题标题】:Count the string by words not char按单词而不是字符计算字符串
【发布时间】:2019-02-13 08:00:18
【问题描述】:

我正在编写这段代码,它可以从 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();
    }

【问题讨论】:

  • “但它不起作用” - 你能解释一下怎么做吗?您想知道words 中匹配了多少单词,或者替换了多少单词? “abc bobo bobo bobo test”是3个字还是1个? “gagaotest”呢?
  • 替换了多少字
  • "abc bobo bobo bobo 测试" 3 bobo
  • 嗨 kyte,请用其他详细信息编辑您的问题(描述 如何 它不起作用 -> 输入是什么,预期输出是什么,实际输出是什么) 而不是将这些细节放在 cmets 中。
  • 约翰,没有单词会被计算,因为没有'gago'

标签: c# string count webbrowser-control


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2017-03-22
    • 2023-03-21
    相关资源
    最近更新 更多