Skip to content

Search In String

A hand-rolled C substring search that returns the index of the first occurrence, written before reaching for strstr.

Published Aug 17, 1998

A from-scratch substring search in the style of the other string utilities here. It walks the haystack one position at a time; whenever the first character matches, an inner loop compares the rest of the needle, and on a full match it records the start index and stops early. Return values: the zero-based index of the first hit, -1 if not found, or -2 if the search string is longer than the source. Today you would just call strstr - but reading this is a good way to see exactly what that function does under the hood, and the two-level loop structure generalizes to searches where you need custom matching rules.

#include <Windows.H>
#include <WindowsX.H>
#include <Stdio.H>
#include <Stdlib.H>

int SearchString(char *Search, char *String)
{
	int StringLength = strlen(String); // source String length
	int SearchLength = strlen(Search); // Search String length
	int ControlLoop = 0; // loop controll used to Search tru String
	int LookingLoop = 0; // loop for looking at sub String
	int StringStart = -1;// place in String where sub String is found

	if(SearchLength > StringLength) //Searched String smaller than what is to be found
		return(-2); // -1 is returned error

	// String is Searched tru as long as it
	//	   is abel to contain sub String

	for(ControlLoop = 0;ControlLoop <= (StringLength-SearchLength);ControlLoop++) // step tru String
	{
		if(String[ControlLoop] == Search[LookingLoop]) //only continue if character apears correct
		{
			while(LookingLoop <= SearchLength) // compare sub String to full String
			{
				if(Search[LookingLoop] == String[LookingLoop + ControlLoop]) // do the characters corospond
					LookingLoop++; // incriment counter if correct
					else LookingLoop = SearchLength + 1; // over step the counter

				if(LookingLoop == SearchLength) // all of the String was Searche through
				{
					StringStart = ControlLoop; // current ControlLoop is the starting position of subString
					ControlLoop = (StringLength - SearchLength) + 1; // end the loop
				}
			}
		}
		LookingLoop = 0;// reset sub lcv;
	}
	return(StringStart); //index of subString, -1 not found,-2 if wrong size
}

int main(int argc, char *argv[])
{
	printf("%d\n",SearchString("..","Hello/Cruel/World/TRYBT/sdfr/erbt/erbt../ertbe/erbt"));

	return 0;
}

The outer loop's first-character pre-check (String[ControlLoop] == Search[0]) is the same optimization naive strstr implementations use to skip positions quickly. The driver prints the index where .. first appears in the sample path-like string.

An unhandled error has occurred. Reload 🗙