c search in string code example
Example 1: check if string in string c
if(strstr(sent, word) != NULL) {
}
Example 2: search a word in a string in c
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
int main()
{
char str[MAX_SIZE];
char word[MAX_SIZE];
int i, j, found;
printf("Enter any string: ");
gets(str);
fflush(stdin);
printf("Enter any word to search: ");
gets(word);
for(i=0; i<strlen(str) - strlen(word); i++)
{
found = 1;
for(j=0; j<strlen(word); j++)
{
if(str[i + j] != word[j])
{
found = 0;
break;
}
}
if(found == 1)
{
printf("'%s' found at index: %d \n", word, i);
}
}
return 0;
}
Example 3: binary search in c
#include<stdio.h>
int BinarySearch(int arr[], int search, int mid, int len){
if(mid == -1 || mid == len+1){
printf("\nSearched Element doesn't exist.");
return 1;
}
else if (search > arr[mid]){
mid++;
BinarySearch(arr,search,mid,len);
return 0;
}
else if (search < arr[mid]){
mid--;
BinarySearch(arr,search,mid,len);
return 0;
}
else if(search == arr[mid]) {
printf("\n Searched Element found at Location %d.",mid);
return 1;
}
}
void main(){
int arr[] = {1,2,3,4,5,6,7,8,9};
int len = sizeof(arr) / sizeof(int);
int mid = (int) (len / 2) + 1;
printf("\n Please Enter Number You Want to Search \n > ");
int search;
scanf("%d",&search);
int Result = BinarySearch(arr,search,mid,len);
}