【问题标题】:Using Linear search使用线性搜索
【发布时间】:2015-04-22 03:37:33
【问题描述】:

我希望能够在我使用 C# 读取的文件中找到所有单词“Monday”。 我可以读取文件,我可以读取第一个星期一并接收它的索引值,但我想要文件中所有星期一的索引值。

    if (ElementS == "2")
    {
        Console.WriteLine("Enter The name of the day e.g. Monday, Tuesday   etc.");
        string ElementA =  Convert.ToString(Console.ReadLine());



        foreach (string Monday in DayLines)
        {
        string Mday = "Monday";
        int Found = Search(DayLines, Mday);
        Console.WriteLine("The index is {0}", Found);
        }

它给出的输出是这样的: // The index is 0 它对文件中的每个元素都这样做,而不仅仅是星期一。

【问题讨论】:

  • 您从不使用 ElementA(来自用户的输入)。什么是 DayLines,从你的代码 sn-p 看不清楚。

标签: c# arrays linear-search


【解决方案1】:

我希望能够在我阅读的文件中找到所有单词“Monday” 使用 C#。

这应该可行:

static void Main()
{
    string text = File.ReadAllText(@"e:\1.txt");
    Regex regex = new Regex("Monday", RegexOptions.IgnoreCase);
    Match match = regex.Match(text);

    while (match.Success)
    {
        Console.WriteLine("'{0}' found at index {1}", match.Value, match.Index);
        match = match.NextMatch();
    }
}

【讨论】:

    【解决方案2】:

    我认为你想做这样的事情:

    internal static void Main(string[] args)
    {
        var dayLines = new List<string>()
            {
                "Monday Monday Monday",
                "Tuesday"
            };
    
        var dayToFind = Console.ReadLine();
    
        foreach (var line in dayLines.Where(l => l.Contains(dayToFind)))
        {
            var index = -1;
            do
            {
                index = line.IndexOf(dayToFind, index + 1);
    
                if (index > -1)
                     Console.WriteLine("The index is {0}", index);
            }
            while (index > -1);
        }
    
        Console.ReadLine();
    }
    

    您需要一个内部循环,它使用前一个索引作为搜索的起点。否则,您将继续获得第一个实例。

    “星期一”的输出:

    The index is 0
    The index is 7
    The index is 14
    

    【讨论】:

      【解决方案3】:

      还有一些使用 LINQ 和改编自 another answer 的扩展方法:

      static class Extensions
      {
          public static IEnumerable<int> AllIndexesOf(this string str, string value)
          {
              for (var index = 0; ; index += value.Length)
              {
                  index = str.IndexOf(value, index, StringComparison.Ordinal);
                  if (index == -1)
                      yield break;
                  yield return index;
              }
          }
      }
      
      ...
      
      var allMondayIndexes = File
                  .ReadAllLines("input.txt")
                  .SelectMany(s => s.AllIndexesOf("Monday"));
      

      我想还有行号会更有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-09-26
        • 1970-01-01
        • 2017-09-04
        • 2017-10-08
        • 1970-01-01
        • 2016-11-13
        • 2014-06-05
        • 1970-01-01
        相关资源
        最近更新 更多