首页 > 解决方案 > 如何使用 indexof 和 substring 在字符串中查找单词?

问题描述

在构造函数中:

var tempFR = File.ReadAllText(file);
GetResults(tempFR);

然后 :

private List<string> GetResults(string file)
            {
                List<string> results = new List<string>();

                string word = textBox1.Text;
                string[] words = word.Split(new string[] { ",," }, StringSplitOptions.None);

                for(int i = 0; i < words.Length; i++)
                {
                    int start = file.IndexOf(words[i], 0);
                    results.Add(file.Substring(start));
                }

                return results;
            }

words 在这种情况下包含 3 个单词 System , public , test 我想找到文件中的所有单词并使用 indexof 和 substring 将它们添加到列表结果中。

现在开始值的方式一直是-1。

清除一些东西。这是 textBox1 的屏幕截图:这就是为什么我使用两个逗号来分割和获取单词的原因。

文本框1

此屏幕截图显示了从 textBox1 拆分后的单词:

用两个逗号就可以了

这是文件字符串内容:

文件内容

我想将文件中的所有单词添加到列表结果中。查看最后一个屏幕截图时,应该有 11 个结果。三倍字采用三倍字制五倍字公。

但变量 start 是 -1

更新 :

尝试过 Barns 解决方案,但对我来说效果不佳。首先是进行搜索的代码,然后循环文件并报告给 backgroundworker :

int numberofdirs = 0;
        void DirSearch(string rootDirectory, string filesExtension, string[] textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
        {
            List<string> filePathList = new List<string>();
            int numberoffiles = 0;
            try
            {
                filePathList = SearchAccessibleFilesNoDistinct(rootDirectory, null, worker, e).ToList();
            }
            catch (Exception err)
            {

            }
            label21.Invoke((MethodInvoker)delegate
                    {
                        label21.Text = "Phase 2: Searching in files";
                    });
            MyProgress myp = new MyProgress();
            myp.Report4 = filePathList.Count.ToString();
            foreach (string file in filePathList)
            {
                try
                {
                    var tempFR = File.ReadAllText(file);

                    _busy.WaitOne();
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        return;
                    }

                    bool reportedFile = false;

                    for (int i = 0; i < textToSearch.Length; i++)
                    {
                        if (tempFR.IndexOf(textToSearch[i], StringComparison.InvariantCultureIgnoreCase) >= 0)
                        {
                            if (!reportedFile)
                            {
                                numberoffiles++;

                                myp.Report1 = file;
                                myp.Report2 = numberoffiles.ToString();
                                myp.Report3 = textToSearch[i];
                                myp.Report5 = FindWordsWithtRegex(tempFR, textToSearch);
                                backgroundWorker1.ReportProgress(0, myp);
                                reportedFile = true;
                            }
                        }
                    }
                    numberofdirs++;
                    label1.Invoke((MethodInvoker)delegate
                    {
                        label1.Text = string.Format("{0}/{1}", numberofdirs, myp.Report4);
                        label1.Visible = true;
                    });
                }
                catch (Exception err)
                {

                }
            }
        }

我已经在 textToSearch 中有单词数组,在 tempFR 中有文件内容,然后我使用 Barns 的第一个解决方案:

private List<string> FindWordsWithtRegex(string filecontent, string[] words)
        {
            var res = new List<string>();

            foreach (var word in words)
            {
                Regex reg = new Regex(word);
                var c = reg.Matches(filecontent);
                int k = 0;
                foreach (var g in c)
                {
                    Console.WriteLine(g.ToString());
                    res.Add(g + ":" + k++);
                }
            }
            Console.WriteLine("Results of FindWordsWithtRegex");
            res.ForEach(f => Console.WriteLine(f));
            Console.WriteLine();

            return res;
        }

但是我在 List res 中得到的结果与 Barns solution/s 中的输出不同这是我得到第一个文件的 List res 的结果:

在这种情况下,两个词 system 和 using 但它只找到 using 3 次,但文件内容中也有 system 3 次。并且输出格式与 Barns 解决方案中的不同:

输出错误

标签: c#winforms

解决方案


这是使用Regex而不是使用的替代方法IndexOf。注意我已经创建了自己的字符串来解析,所以我的结果会有点不同。


编辑

    private List<string> FindWordsWithCountRegex(string filecontent, string[] words)
    {
        var res = new List<string>();

        foreach (var word in words)
        {
            Regex reg = new Regex(word, RegexOptions.IgnoreCase);
            var c = reg.Matches(filecontent).Count();
            res.Add(word + ":" + c);
        }

        return res;
    }

推荐阅读