The first question is: Write a function to delete a string.Str1String contained inStr2. This question is not difficult, but there is a KMP OptimizationAlgorithmFor more information, see.
The second question is: the given stringAAndB,OutputAAndB. MyCodeYes:
# Include <stdio. h> # include <string. h> void utmost_comstr (char * S1, char * S2) // imagine: S1 is longer {int maxlength = 0, length = 0, I = 0; char * P1 = S1, * p1_1 = S1, * P2 = S2, * p2_2 = S2; char * maxstartaddr = S1; while (* P1! = 0) {If (* P1 = * P2) {length ++; If (length> maxlength) {maxlength = length; maxstartaddr = p1_1;} P1 ++; p2 ++;} else if (* P1! = * P2) & * P2! = 0) {length = 0; P1 = p1_1; p2_2 ++; P2 = p2_2;} else if (* P2 = 0) {length = 0; p1_1 = S1 ++; P1 = p1_1; p2_2 = S2; P2 = p2_2 ;}} printf ("max length is % d \ n", maxlength ); printf ("the longest same string is: \ n"); While (I <maxlength) {putchar (* maxstartaddr); I ++; maxstartaddr ++ ;}} void main () {char * S1 = "aocdfe"; char * S2 = "pmcdfa"; utmost_comstr (S1, S2 );}
I read the algorithms written by others on the Internet and found several convenient functions for operating strings:
Char * commanstring (char character string [], char longstring []) {int I, j; char * substring = malloc (256); If (strstr (longstring, character string )! = NULL) // If ......, Then return repeated stringreturn response string; for (I = strlen (distinct string)-1; I> 0; I --) // otherwise, start the cyclic calculation {for (j = 0; j <= strlen (character string)-I; j ++) {memcpy (substring, & character string [J], I); substring [I] = '\ 0 '; if (strstr (longstring, substring )! = NULL) return substring ;}} return NULL;} Main () {char * str1 = malloc (256); char * str2 = malloc (256); char * comman = NULL; gets (str1); gets (str2); If (strlen (str1)> strlen (str2) // put the short string in front of comman = commanstring (str2, str1 ); elsecomman = commanstring (str1, str2); printf ("the longest comman string is: % s \ n", comman );}
In this algorithmThe essence is the strstr () function., Learned here