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

Write a C program to find last occurrence of a word in given string using loop. How to find last occurrence of a word in given string using loop in C programming. Program to search last index of a given word in a string in C.

Example:
Input string: I love programming. I love CodeforWin.
Input word: love
Output last index: 22

Required knowledge

Basic C programming, Loop, String

Before moving on to this It is recommended that you must know how to find last occurrence of a character in given string and how to search for a word in a string. As logic to this program is depended upon both the above programs.

Program to find last occurrence of word in string

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

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

int main()
{
    char string[MAX_SIZE];
    char word[MAX_SIZE];
    int i, j, index, found;
    int stringLen, wordLen;

    /*
     * Reads string and word from user
     */
    printf("Enter any string: ");
    gets(string);
    printf("Enter any word to search: ");
    gets(word);

    index = -1;
    stringLen = strlen(string); //Finds length of string
    wordLen = strlen(word); //Finds length of word


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

        //If word have been found then store the current found index
        if(found == 1)
        {
            index = i;
        }
    }

    if(index == -1)
    {
        printf("'%s' not found.\n", word);
    }
    else
    {
        printf("Last index of '%s' : %d\n", word, index);
    }

    return 0;
}


Output
Enter any string: I love programming. I love CodeforWin.
Enter any word to search: love
Last index of 'love' : 22

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment