繁体   English   中英

如何使用 indexof 和 substring 在字符串中查找单词?

[英]How can I use indexof and substring to find words in a string?

在构造函数中:

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

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

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

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

文本框1

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

用两个逗号就可以了

这是文件字符串内容:

文件内容

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

但变量 start 是 -1

更新:

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

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 中的 output 不同,这是我得到第一个文件的 List res 的结果:

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

输出错误

这是使用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;
    }

简单更改此部分并使用单个字符,通常是空格而不是逗号:

string[] words = word.Split(' ');
int start = file.IndexOf(words[i],0);

如果找不到该单词,则 start 将为-1
MSDN:IndexOf(字符串,Int32)

for(int i = 0; i < words.Length; i++)
{
    int start = file.IndexOf(words[i], 0);
    // only add to results if word is found (index >= 0)
    if (start >= 0) results.Add(file.Substring(start));
}

如果你想要单词的所有外观,你需要一个额外的循环

int fileLength = file.Length;
for(int i = 0; i < words.Length; i++)
{
    int startIdx = 0;
    while (startIdx < fileLength ){
        int idx = file.IndexOf(words[i], startIdx]);
        if (start >= 0) {
            // add to results
            results.Add(file.Substring(start));
            // and let Word-search continue from last found Word Position Ending
            startIdx = (start + words.Length);
        }

    }
    int start = file.IndexOf(words[i], 0);
    // only add to results if word is found (index >= 0)
    if (start >= 0) results.Add(file.Substring(start));
}

也许你想要一个不区分大小写的搜索
file.IndexOf(words[i], 0, StringComparison.CurrentCultureIgnoreCase); MSDN:字符串比较器 Class

暂无
暂无

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

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