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

C - Programming: no ios stream library should be used. Your code should be able

ID: 3719911 • Letter: C

Question

C - Programming: no ios stream library should be used. Your code should be able to work for "code blocks"

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 output should be 4 since the longest common substring is “abcd”. Hint: rank the prefixes.

The output should be able to display the longest common substring.

Explanation / Answer

CODE:

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

void longestCommon(char *str, int len) {
char longest[100] = "";

for(int i=0; i<len-1; i++) {
for(int j=i+1; j<len; j++) {
// we will divide complete stirng to 2 parts
// index i to index j(exclusing)
// index j to end
// If first string is found in second string, then it is a common string
// if it is maximum length, we will keep updating our answer..

char first[100];
strncpy(first, str+i, j-i);

char second[100];
strncpy(second, str+j, len-j);

// check if substring is present in str
if(strstr(second, first) != NULL) {

if(strlen(first) > strlen(longest)) {
strcpy(longest, first);
}
}
}
}

printf("Longest String: %s ", longest);
}

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

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

longestCommon(s, strlen(s));
return 0;
}