c语言中的子串比较

时间:2013-11-09 16:15:59

标签: c string chars

我的任务如下:

在字符串匹配中,我们正在寻找另一个字符串(模式)的实例(文本)。我们正在寻找具有最少故障数(不匹配)的实例。

例如,如果模式是“camb”而文本是“caammbd”,我们比较“position”: 1.比较“camb”和“caam”,显示2个不匹配(m表示a和b表示m)。 2.将“camb”与“aamm”进行比较,其中显示2个不匹配(m表示a和b表示m)。 等等....

我的prgoram从用户读取两个字符串并尝试找到最小的数字并返回其“位置”:

int misPattern(char str[], char pattern[]){
    int count = 0, maxCount = 0, worstPattern = 0, i = 0, j = 0, z = 0,
    patternNum = 1; 
    /*in order to make minimal tests, we must have each string's length*/
    int testsMade = 0;
    int numOfTests = (strlen(str, MAX_LEN + 1)) - (strlen(pattern, MAX_LEN + 1));
    while (str[i] != '\0' && testsMade<=numOfTests){
        z = i; count = 0;
        while (pattern[j] != '\0'){
            if (str[z] != pattern[j])
                count++;
            j++;
            z++;
        }
        j = 0;
        i++;
        if (count > maxCount){
            maxCount= count;
            worstPattern = patternNum;
        }
        patternNum++;
        testsMade++;
    }
    printf("%d\n", count);
    return worstPattern;
}

最差图案应代表最少不匹配的位置。

正如您可能想象的那样,这里出了点问题。从调试器来看,似乎我的比较并不顺利。正如dubugger所示,字符串读得很好。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

int misPattern(char str[], char pattern[]){
    int count = 0, minCount = 0, worstPattern = 0, i = 0, j = 0, z = 0, patternNum = 0; 
    /*in order to make minimal tests, we must have each string's length*/
    int testsMade = 0;
    int numOfTests = (strlen(str, MAX_LEN + 1)) - (strlen(pattern, MAX_LEN + 1));

    /*if the pattern is longer
    than the text than return -1, and 
     if the strings are   `equal         also     return -1*/`
    if (strcmp(str,pattern)<=0)
        return -1;

    /*initial value for minCount. we have to make sure minCount is initilized at least once*/
    while (str[i] != '\0' && (minCount == 0) && testsMade<=numOfTests){
        z = i;
        while (pattern[j] != '\0'){
            if (str[z] != pattern[j])
                minCount++;
            j++;
            z++;
        }
        testsMade++;
        j = 0;
        i++;
        patternNum++;
    }

        printf("number of first minimal mismatches is %d\n", minCount);
        printf("i is %d j is %d\n", i, j);

    while (str[i] != '\0' && testsMade<=numOfTests){
        z = i; count = 0;
        while (pattern[j] != '\0'){
            if (str[z] != pattern[j])
                count++;

            j++;
            z++;
        }
        j = 0;
        i++;
        if (count < minCount){
            minCount= count;
            worstPattern = patternNum;
        }
        patternNum++;
        testsMade++;
    }

    return worstPattern;
}

在理解我的错误之后,这是我的最终计划。谢谢大家。