搜索字符串以查看单词是否出现多次

时间:2018-06-01 14:11:34

标签: c# streamreader

我需要检查给定的单词是否包含在路径内的一行中,然后打印出来。这是我的代码:

using (StreamReader reading = new StreamReader(path))
{
   string user= Console.ReadLine();
   string line = user;
   Console.WriteLine();
   while ((line = reading.ReadLine()) != null)
   {
       if (line.Contains(user))
       {
          Console.WriteLine(line);
       }
    }
 }

这是有效的,但如果在流中找到两次这个单词,它会给出两个字符串作为输出。我怎样才能检查这个单词是否被发现两次?

3 个答案:

答案 0 :(得分:1)

如果您只想显示用户的行并显示包含user的行数的总数,您可以使用一些LINQ轻松完成此操作:

var linesWithUser = File.ReadLines(filePath).Where(x => x.Contains(user)).ToList();

//Prints the count
Console.WriteLine(linesWithUser.Count);

//Prints all the lines that contain the user, maybe do other things...
foreach(var line in linesWithUser)
{
    Console.WriteLine(line);
}

答案 1 :(得分:0)

类似的东西:

bool ContainsWordMultipleTimes(string word, string input)
{
    var regex = new Regex(string.Format(@"\b{0}\b", word), 
                          RegexOptions.IgnoreCase);
    return regex.Matches(input).Count > 1;
}

甚至可以像这样扩展string

public static class StringWordsExtensions
{
    public static bool ContainsMultipleTimes(this string input, string word)
    {
        var regex = new Regex(string.Format(@"\b{0}\b", word),
                              RegexOptions.IgnoreCase);
        return regex.Matches(input).Count > 1;
    }
}

答案 2 :(得分:0)

把你的计数放在外面,就像这样:

int count = 0;
    string line = null;
    while ((line = reading.ReadLine()) != null)
    {
        if (line.Contains(user))
        {
            count++;
        }
    }
    if (count > 0)
    {
        Console.WriteLine(user +" found " + count +" time");
    }
    else
    {
        Console.WriteLine(user + " not found!");
    }