[C] 纯文本查看 复制代码 //找出多个字符串中的最大公共子字符串,如“nbitheimanb”和“itheia”的最大子串是:”ithei”。(C语言)
#import <Foundation/Foundation.h>
#include <string.h>
//检索两个字符是否匹配
int isMatching(char str1, char str2);
//根据范围截取字符串
char* substringWithRange(char *str, int lenth, int x, int y);
//判断字符串是否包含
int containsString(char *str1, int str1Len, char *str2, int str2Len);
int isMatching(char str1, char str2) {
if (str1 == str2) {
return 1;
}
return 0;
}
char* substringWithRange(char *str, int lenth, int x, int y) {
char *temp = calloc(lenth, sizeof(char));
int index = 0;
while (y > 0) {
temp[index++] = str[x++];//s
y--;
}
return temp;
}
int containsString(char *str1, int str1Len, char *str2, int str2Len) {
int index = 0;
for (int i = 0; i < str1Len; i++) {
index = i;
for (int j = 0; j < str2Len; j++) {
if (!isMatching(str1[index], str2[j])) {
break;
}else if (j == str2Len - 1) {
return 1;
}
index++;
}
}
return 0;
}
int main(int argc, const char * argv[]) {
char *str1 = "asihjktwditheimasdw";
char *str2 = "xxitititheimaxx";
int len1 = (int)strlen(str1);
int len2 = (int)strlen(str2);
char *str = calloc(len2, sizeof(char));
for (int i = 0; i < len1; i++) {
for (int j = 1 ; j <= len1 - i; j++) {
//截取字符串
char *temp = substringWithRange(str1, len1, i, j);
printf("%s\n",temp);
//如果str2字符串包含temp字符串
if (containsString(str2, len2, temp, (int)strlen(temp))) {
if (str == NULL) {
strcpy(str, temp);
}else {
if ((int)strlen(str) < (int)strlen(temp)) {
strcpy(str, temp);
}
}
}
free(temp);
}
}
printf("%s\n",str);
free(str);
return 0;
}
|