Skip to content

Instantly share code, notes, and snippets.

@tuldok89
Created May 19, 2012 06:08
Show Gist options
  • Save tuldok89/2729548 to your computer and use it in GitHub Desktop.
Save tuldok89/2729548 to your computer and use it in GitHub Desktop.
Find a string (C)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *haystack,*needle,*loc,*tmphay;
int x;
x = 0;
haystack = (char*)malloc(sizeof(char) * 256);
needle = (char*)malloc(sizeof(char) * 20);
printf("Enter a string: ");
gets(haystack);
printf("Enter a string to find: ");
gets(needle);
tmphay = haystack;
do
{
loc = strstr(tmphay,needle);
if (loc != NULL)
{
if (x == 0)
printf("String found at positions: ");
printf("%lu ", (loc - haystack) + 1);
x++;
}
tmphay = loc + 1;
}
while (loc != NULL);
if (x == 0)
printf("No string found.");
free(haystack);
free(needle);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment