gpt4 book ai didi

c - C语言子串比较

转载 作者:行者123 更新时间:2023-11-30 17:44:43 24 4
gpt4 key购买 nike

我的任务如下:

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

例如,如果模式是“camb”并且文本是“caammbd”,我们比较“位置”: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;
}

最坏的模式应该代表最少不匹配的位置。

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

感谢您的帮助。

最佳答案

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

这是我在了解自己的错误之后的最终程序。谢谢大家。

关于c - C语言子串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19878146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com