Created
May 19, 2012 06:08
-
-
Save tuldok89/2729548 to your computer and use it in GitHub Desktop.
Find a string (C)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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