简体   繁体   中英

Check if string is similar to another string without n characters in c

I try to write a program that checks if a string is similar to another string without n characters.

For example
S=swsystems and t=ssysems and n=2 will return 1, because it can omit w and t from s .

I tried:

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;
}

But, I also have to support omitting letters in the middle of the word.

How can I do this?

Here is a code that should do the job

/* 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)? %d\n", s, t, n, similar(s, t, n));
    return 0;
}

Usage

$ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM