C program to search all occurrences of a word in a string

Category: C Program

Learn how to write a C program to search all occurrences of a word in a given string. This tutorial includes step-by-step instructions, code implementation, and explanations to help you understand the process of searching for a word in a string using basic string manipulation techniques and the strstr function.

Searching for a word within a string is a common operation in text processing. This task can be broken down into finding all occurrences of a specific word within a larger text string. This article will guide you through creating a C program to accomplish this.

Introduction

In this article, we will write a C program that searches for all occurrences of a word in a given string. We will use basic string manipulation techniques to achieve this. The program will take a string and a word as input and then search for all occurrences of the word in the string, printing the starting index of each occurrence.

Steps to Solve the Problem

  1. Input the String and Word: We will read the input string and the word to be searched.
  2. Search for the Word: Iterate through the string to find all occurrences of the word.
  3. Print the Indices: Output the starting index of each occurrence of the word.

Write a C program to search all occurrences of a word in a string

Here is the C program to search for all occurrences of a word in a given string:

#include <stdio.h>
#include <string.h>

int main() {
    char str[100], word[20];
    int strLen, wordLen;
    int found = 0;

    // Input the string
    printf("Enter the string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0'; // Removing trailing newline character

    // Input the word to be searched
    printf("Enter the word to search: ");
    scanf("%s", word);

    strLen = strlen(str);
    wordLen = strlen(word);

    // Search for all occurrences of the word in the string
    for (int i = 0; i <= strLen - wordLen; i++) {
        int j;
        for (j = 0; j < wordLen; j++) {
            if (str[i + j] != word[j])
                break;
        }
        if (j == wordLen) {
            printf("Word found at index: %d\n", i);
            found = 1;
        }
    }

    if (!found) {
        printf("Word not found in the string.");
    }

    return 0;
}

Output

Enter the string: time and time again, the rain keeps falling down
Enter the word to search: time
Word found at index: 0
Word found at index: 9

Explanation of the Code

  1. Input Handling: We read the input string using fgets and remove the trailing newline character. We then read the word to be searched using scanf.
  2. Length Calculation: We calculate the lengths of the input string and the word.
  3. Search Loop:
    • We use a nested loop to compare the word with substrings of the input string.
    • The outer loop iterates over each position in the string where the word could start.
    • The inner loop checks if the word matches the substring starting at the current position.
    • If a match is found, we print the starting index.
  4. Match Check: After the loop, we check if the word was found. If not, we print a message indicating that the word was not found.

Using strstr for Simplification

The strstr function can also be used to find all occurrences of a word in a string. Here’s how you can use strstr for this task:

#include <stdio.h>
#include <string.h>

int main() {
    char str[100], word[20];
    char* pos;
    int index;

    // Input the string
    printf("Enter the string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0'; // Removing trailing newline character

    // Input the word to be searched
    printf("Enter the word to search: ");
    scanf("%s", word);

    pos = str;
    int found = 0;

    // Search for all occurrences of the word in the string
    while ((pos = strstr(pos, word)) != NULL) {
        index = pos - str;
        printf("Word found at index: %d\n", index);
        pos += strlen(word);
        found = 1;
    }

    if (!found) {
        printf("Word not found in the string.");
    }

    return 0;
}

Explanation of strstr

The strstr function finds the first occurrence of a substring in a string. It returns a pointer to the first occurrence of the substring, or NULL if the substring is not found. By advancing the pointer and calling strstr repeatedly, we can find all occurrences of the word in the string.


Recommended Posts