Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C - Programming: Please, this is for those who use CodeBlocks only, or any codin

ID: 3720047 • Letter: C

Question

C - Programming: Please, this is for those who use CodeBlocks only, or any coding software similar to that.  

Q1. Read from console input a string (length < 100) and print the length of its longest common substring.

Eg.: Input: “abcdxyzefgabcdxyefxyz” Here the common substrings are substrings that appear more than one times in the given input.

So in this example, the common substrings are “abcd”, “xyz” and “ef”. Your ouput should be 4 since the longest common substring is “abcd”.

Hint: rank the prefixes.

Explanation / Answer

Hi,

Please find the below program to find the longest substring. In example which you provided "abcdxyzefgabcdxyefxyz" longest substring is "abcdxy" as that is the substring which repeated twice.

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

void longestCommonSubstring(char *cstr, int length) {
char longString[100] = "";

for(int i=0; i<length-1; i++) {
for(int j=i+1; j<length; j++) {
char fStr[100];
strncpy(fStr, cstr+i, j-i);

char secStr[100];
strncpy(secStr, cstr+j, length-j);
if(strstr(secStr, fStr) != NULL) {

if(strlen(fStr) > strlen(longString)) {
strcpy(longString, fStr);
}
}
}
}

printf("Longest common sub string: %s ", longString);
}

int main(void) {
char str1[100];

printf("Enter the input string: ");
scanf("%s", str1);

if(strlen(str1) > 100){
printf("String should be of size less than 100 ");
return 0;
}

longestCommonSubstring(str1, strlen(str1));
return 0;
}

Output:

Enter the input string:

abcdxyzefgabcdxyefxyz

Longest common sub string : abcdxy