Check if a String Contains Repeated Substrings in C

To check if a string contains repeated substrings in C, you can use various methods such as the strstr function for simple substring search or manual nested loops to count occurrences. Both approaches allow you to determine if a given substring appears more than once in the string.


Example 1: Using strstr Function

In this example, we will check if a given substring appears repeatedly in a string by using the strstr function. The strstr function finds the first occurrence of the substring, and we then continue the search from the next position to count subsequent occurrences.

main.c

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

int main() {
    char str[] = "hello world, hello C programmers!";
    char substr[] = "hello";
    int count = 0;
    
    // Pointer to store the result of strstr function
    char *pos = str;
    
    // Use strstr to search for the substring repeatedly
    while ((pos = strstr(pos, substr)) != NULL) {
        count++;
        pos += strlen(substr);  // Move pointer past the found substring
    }
    
    printf("The substring \"%s\" appears %d times.\\n", substr, count);
    return 0;
}

Explanation:

  1. We declare a string str and a substring substr that we want to search for.
  2. The integer variable count is initialized to 0 to keep track of the number of occurrences.
  3. The pointer pos is set to the beginning of str and is used to locate occurrences of substr using strstr.
  4. Inside the while loop, we search for substr in str starting from the current position.
  5. If strstr returns a non-NULL pointer, it means an occurrence is found, so we increment count.
  6. We then move the pointer pos forward by the length of substr to continue searching for additional occurrences.
  7. Finally, we print the total count of occurrences.

Output:

The substring "hello" appears 2 times.

Example 2: Using Nested Loops for Manual Substring Matching

In this example, we will manually check for repeated occurrences of a substring by iterating through the main string with nested loops. This approach does not use any library functions for substring searching, giving you a better understanding of the underlying process.

main.c

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

int main() {
    char str[] = "abcabcabcd";
    char substr[] = "abc";
    int count = 0;
    int str_len = strlen(str);
    int substr_len = strlen(substr);
    
    // Loop through the main string
    for (int i = 0; i <= str_len - substr_len; i++) {
        int j;
        // Check if substring matches starting at index i
        for (j = 0; j < substr_len; j++) {
            if (str[i + j] != substr[j]) {
                break;
            }
        }
        // If full substring was found, increment count
        if (j == substr_len) {
            count++;
        }
    }
    
    printf("The substring \"%s\" appears %d times.\\n", substr, count);
    return 0;
}

Explanation:

  1. We declare the main string str and the substring substr to be searched.
  2. Variables str_len and substr_len store the lengths of str and substr respectively.
  3. The outer for loop iterates through str from index 0 to str_len - substr_len to ensure enough characters remain for a possible match.
  4. The inner for loop compares the substring with a segment of str starting at index i.
  5. If a mismatch is found, the inner loop breaks; otherwise, if j equals substr_len, it indicates a complete match, and count is incremented.
  6. Finally, the total count of repeated substrings is printed.

Output:

The substring "abc" appears 3 times.