I’m trying to make a simple substring search using the brute force technique but I’m getting an error which I can’t see. I’m quite new to programming so please keep that in mind. The problem might be very simple.
using System;
using System.Collections;
using System.Collections.Generic;
namespace SubstringSearch
{
class Program
{
static void Main(string[] args)
{
Console.Write("Please enter some letters: ");
string sequence = Console.ReadLine();
Console.Write("Enter the sequence you want to search for: ");
string pattern = Console.ReadLine();
Console.WriteLine(Search(pattern, pattern.Length, sequence, sequence.Length));
Console.ReadLine();
}
public static int Search(string pattern, int patternLength, string sequence, int stringLength)
{
int i;
int j;
if (stringLength >= patternLength)
{
for (j = 0; j <= (stringLength - patternLength); j++)
{
for (i = 0; i < patternLength && pattern[i] == sequence[i + j]; i++);
if (i >= patternLength)
return j;
else
return -1;
}
}
else
return -1;
}
}
}
So I’m getting one error and one warning. First it tells me that not all code paths return a value ( in Search() ). I can’t see why. Second I get a warning that my integer ‘j’ is unreachable in the first for-loop (at ‘j++’).
Please help! I’m sure the answer is quite simple, but I just can’t see it.
The issue seems to lie in your second for loop. Try this:
That should remove all warnings and errors and compile. Why are you not using the
.Contains()method?