Naive String Search Algorithm

The Naive String Search Algorithm, also known as the Brute Force Algorithm, is a simple and straightforward approach for searching a pattern or substring within a larger string or text. This algorithm's basic idea is to iterate through the text, comparing each character of the text with the characters of the pattern. When a match is found, the algorithm moves through the pattern, checking if subsequent characters also match. If a complete match is found, the algorithm returns the starting position of the match in the text. Otherwise, it moves on to the next character in the text and repeats the process until all possible matches have been checked. Although the Naive String Search Algorithm is simple to understand and implement, it is not the most efficient solution for pattern matching. Its worst-case time complexity is O(n*m), where n is the length of the text and m is the length of the pattern. This can lead to slow performance when searching for patterns in large texts or when dealing with multiple patterns. However, despite its inefficiency, the Naive String Search Algorithm can still be useful in cases where the pattern being searched is relatively small or when the text has a limited number of characters, as it requires no pre-processing or additional data structures.
using System;
using System.Collections.Generic;

// Implements the traditional naive string matching algorithm in C# for TheAlgorithms/C-Sharp.
namespace Algorithms.Strings
{
   /// <summary>
   /// Implements the traditional naive string matching algorithm in C#.
   /// </summary>
   public static class NaiveStringSearch
   {
      /// <summary>
      /// NaiveSearch(Content, Pattern) will return an array containing each index of Content in which Pattern appears.
      /// Cost:  O(n*m).
      /// </summary>
      /// <param name="content">The text body across which to search for a given pattern.</param>
      /// <param name="pattern">The pattern against which to check the given text body.</param>
      /// <returns>Array containing each index of Content in which Pattern appears.</returns>
      public static int[] NaiveSearch(string content, string pattern)
      {
         int m = pattern.Length;
         int n = content.Length;
         List<int> indices = new List<int>();
         for (int e = 0; e <= (n - m); e++)
         {
            int j;
            for (j = 0; j < m; j++)
            {
               if (content[e + j] != pattern[j])
               {
                  break;
               }
            }

            if (j == m)
            {
               indices.Add(e);
            }
         }

         return indices.ToArray();
      }
   }
}

LANGUAGE:

DARK MODE: