检查字符串是否类似于 c 中没有 n 个字符的另一个字符串



我尝试编写一个程序来检查一个字符串是否与另一个没有n个字符的字符串相似。

例如
S=swsystemst=ssysemsn=2将返回 1,因为它可以从s中省略wt

我试过了:

int similar (char *s, char *t, int n){
s_len = strlen(s);
t_len = strlen(t);
if(s_len - n != t_len){
return 0;
}
char new[30];
for(int i = 0; i < s_len - n; i++){
new[i] = s[i];
}
if(strcmp(t, new)){
return 1
}
for(int i = n - 1; i < s_len; i++){
new[i] = s[i];
}
if(strcmp(t, new)){
return 1
}
return 0;
}

但是,我还必须支持在单词中间省略字母。

我该怎么做?

这是一个应该完成这项工作的代码

/* File : main.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int similar(const char *s1, const char *s2, int diff_max) {
const char *str_small = NULL, *str_long = NULL;
int diff_counter = 0;
size_t len_s1 = strlen(s1), len_s2 = strlen(s2);
// If the length difference exceeds diff_max -> fail the test
if ((len_s1 + diff_max) != len_s2 && (len_s2 + diff_max) != len_s1)
return 0;
// Set str_small to the smallest string and str_long the longest
if (len_s1 < len_s2) {
str_small = s1;
str_long = s2;
} else {
str_small = s2;
str_long = s1;
}
// Check, in order, that no more than diff_max caracters differs
do {
if (*str_small != *str_long) {
if (++diff_counter > diff_max)
break;
}
else
++str_small; // go forward for str_small only when we matched
++str_long; // go forward for str_long all the time
} while(*str_small);
return diff_counter == diff_max;
}
int main(int argc, char const *argv[]) {
const char *s = argv[1];
const char *t = argv[2];
int n = atoi(argv[3]);
printf("Are they similar '%s' '%s' (n=%d)? %dn", s, t, n, similar(s, t, n));
return 0;
}

用法

$ make main
$ ./main swsystems ssysems 2
Are they similar 'swsystems' 'ssysems' (n=2)? 1
$ ./main swsystems ssysems 3
Are they similar 'swsystems' 'ssysems' (n=3)? 0
$ ./main kayak kaytak 1
Are they similar 'kayak' 'kaytak' (n=1)? 1
$ ./main kaytak kayak 1
Are they similar 'kaytak' 'kayak' (n=1)? 1
$ ./main kaytka kayak 1
Are they similar 'kaytka' 'kayak' (n=1)? 0

最新更新