-2

假设有一个包含文本的文本文件(例如:-任何网站的内容)。现在,如果我想从文本文件中匹配字符串strA,即段落,即文本文件中的文本说 a.txt 是否包含字符串strA

怎么比较呢?

4

2 回答 2

1

我会做类似的事情:

bool containsString  = File.ReadAllText(@"C:\test.txt").Contains("strA");
于 2013-10-02T13:00:22.360 回答
0

这是您正在寻找的一个非常基本的实现。有很多改进要做。

    /// <summary>
    /// Finds the text files that contain paragraph.
    /// </summary>
    /// <param name="paragraph">The paragraph to check for.</param>
    /// <param name="textFilePaths">A list of paths to text files to check.</param>
    /// <returns></returns>
    List<string> FindFilesWithParagraph(string paragraph, List<string> textFilePaths)
    {
        List<string> foundPaths = new List<string>(); // list of paths to text files w/ paragraph

        foreach (string path in textFilePaths) // iterate through each file
        {
            if (!File.Exists(path)) // check files actually exist
                throw new ArgumentException();

            using (var sr = new System.IO.StreamReader(path))
            {
                if (sr.ReadToEnd().Contains(paragraph)) // read contents of file
                    foundPaths.Add(path); // and add it to list if it contains the paragraph
            }
        }

        return foundPaths;
    }
于 2013-10-02T13:22:00.927 回答