C Program to Find Common Parts of Two Strings

Introduction

In this article, we will explore a C program to find the common parts of two strings.

Strings are a fundamental data type in programming, and it’s often necessary to compare and analyze them.

Also Read: Print Contents of File in Reverse Order in C

The c program we will develop will allow us to find and extract the common parts of two strings, helping us solve a variety of practical problems.

Let’s dive into the details and understand how to implement this program step by step.

Understanding the Problem

Before we start writing the C program, let’s gain a clear understanding of the problem at hand.

Suppose, we have two strings and our task is to find the common parts between them. In other words, we need to identify the substrings that exist in both strings.

Also Read: Search a Character in a String Using a Pointer in C

The order and position of the common parts do not matter; we are only interested in the content.

Algorithm to Find Common Parts

To find the common parts of two strings, we can follow a simple algorithmic approach. Here are the steps:

  1. Accept the two input strings from the user.
  2. Initialize a variable to keep track of the starting index of the common parts.
  3. Iterate over the first string character by character.
  4. Within the first loop, iterate over the second string character by character.
  5. Compare the characters at the current positions of both strings.
  6. If the characters match, it means we have found a potential common part.
  7. Start a nested loop to check the consecutive characters in both strings.
  8. If all the characters match consecutively, we have found a common part.
  9. Print or store the common part for further processing.
  10. Continue the outer loop and repeat the process until we reach the end of the first string.
  11. Display the common parts found between the two strings.

Also Read: C Program To Read Two Files Simultaneously

Implementation of the C Program

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

void findCommonParts(char str1[], char str2[]) {
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    
    for (int i = 0; i < len1; i++) {
        for (int j = 0; j < len2; j++) {
            if (str1[i] == str2[j]) {
                int m = i, n = j;
                while (m < len1 && n < len2 && str1[m] == str2[n]) {
                    m++;
                    n++;
                }
                int commonLen = m - i;
                if (commonLen > 0) {
                    printf("Common Part: ");
                    for (int k = i; k < i + commonLen; k++) {
                        printf("%c", str1[k]);
                    }
                    printf("\n");
                }
            }
        }
    }
}

int main() {
    char str1[100], str2[100];
    printf("Enter the first string: ");
    gets(str1);
    printf("Enter the second string: ");
    gets(str2);
    printf("\nCommon Parts:\n");
    findCommonParts(str1, str2);
    
    return 0;
}

Explanation of the Code

The code above follows the algorithm we discussed earlier. It accepts two strings from the user, iterates over them, and finds the common parts.

Also Read: Armstrong Number in C Programming

Let’s go through the main sections of the code:

  1. The findCommonParts function takes two string arrays as input and finds the common parts between them.
  2. It uses nested loops to compare each character in the two strings.
  3. If a matching character is found, it enters a nested loop to check for consecutive matching characters.
  4. The common part is printed to the console.

Also Read: C Program to Find the Inverse of 2×2 Matrix

FAQs

Q1: How does the program handle case-sensitive strings?

The program is case-sensitive, which means it distinguishes between uppercase and lowercase characters. For example, “hello” and “Hello” would be treated as different strings, and their common parts would not be identified. To make the program case-insensitive, we can convert both strings to lowercase or uppercase using the tolower() or toupper() functions before performing the comparison.

Q2: Can the program handle strings of different lengths?

Yes, the program can handle strings of different lengths. It compares each character of the first string with each character of the second string, regardless of their lengths. The common parts can be found even if the strings have different sizes.

Q3: How are repeated common parts handled?

The program will identify repeated common parts if they exist. For example, if the strings are “banana” and “an”, the common part “an” will be found twice in the first string. The program will print both occurrences of the common part.

Q4: Are spaces and punctuation considered in the comparison?

Yes, spaces and punctuation are considered in the comparison. The program treats all characters equally and checks for consecutive matching characters, including spaces and punctuation marks. If the common parts include spaces or punctuation, they will be identified and displayed.

Q5: Can the program handle special characters and non-alphabetic characters?

Yes, the program can handle special characters and non-alphabetic characters. It compares the characters as they are and does not exclude any specific characters from the comparison. The program will find common parts regardless of the presence of special or non-alphabetic characters.

Q6: How efficient is the algorithm used in the program?

The algorithm used in the program has a time complexity of O(m * n), where m and n are the lengths of the input strings. This means that the program’s runtime increases with the product of the lengths of the strings. For larger strings, the program may take longer to execute. However, for most practical cases, the performance is reasonable.

Also Read: C Program to Copy the Contents of One File into Another File

Conclusion

In this article, we explored a C program to find the common parts of two strings. We discussed the algorithmic approach and provided a step-by-step implementation.

The program allows us to identify and extract the common substrings between two strings, providing a solution for various applications.

Also Read: 25 Tricky Questions on Pointers in C: Explained and Answered

By understanding the problem and following the code explanation, you can now use this program to find common parts in your own C projects.