searching a word in a string in c code example

Example 1: find character from string c count

#include <stdio.h>
#include <string.h>
 
int main()
{
    char s[1000],c;  
    int i,count=0;
 
    printf("Enter  the string : ");
    gets(s);
    printf("Enter character to be searched: ");
    c=getchar();
    
    for(i=0;s[i];i++)  
    {
    	if(s[i]==c)
    	{
          count++;
		}
 	}
     
	printf("character '%c' occurs %d times \n ",c,count);
 
 	 
     
    return 0;
}

Example 2: search a word in a string in c

/**
 * C program to find last occurrence of a word in given string
 */

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[MAX_SIZE];
    char word[MAX_SIZE];
    int i, j, found;

    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    fflush(stdin);
    printf("Enter any word to search: ");
    gets(word);

    /*
     * Run a loop from starting index of string to
     * length of string - word length
     */
    for(i=0; i<strlen(str) - strlen(word); i++)
    {
        // Match word at current position
        found = 1;
        for(j=0; j<strlen(word); j++)
        {
            // If word is not matched
            if(str[i + j] != word[j])
            {
                found = 0;
                break;
            }
        }

        // If word have been found then print found message
        if(found == 1)
        {
            printf("'%s' found at index: %d \n", word, i);
        }
    }

    return 0;
}

Tags:

Misc Example