我想比较字符串,每个字符与所有其他字符,无论它们位于相同位置还是在另一个位置具有相同的数字。
我不知道如何正确使用字符串比较,我尝试过 for
和while
循环 count
但我不知道。
我的问题是这样的。例如。 我的密码是1234。 我的测试是1234。 在这种情况下,我有 4 人死亡。因为数字的位置是一样的。但在这种情况下。 我的密码是1234。 我的测试是1243。 我有 2 人死亡,因为 1 和 2 处于正确位置,但 4 和 3 处于其他位置,但它们位于另一串中。 在这种情况下,我有 2 人死亡和 2 人受伤。 抱歉我的英语不太好。感谢您的帮助..
最佳答案
strcmp
不会给出给定字符串中匹配的字符数。尝试下面的代码,它将给出输入字符串中匹配字符的数量。
#include <string.h>
int GetMatchingChars (const char *s1, const char *s2)
{
int len1;
int len2;
int count = 0;
int minLen = 0;
char *shortPtr = NULL;
char *longPtr = NULL;
/* First check if the string are equal, return either len, no need to go further */
if (strcmp (s1, s2) == 0) {
return strlen(s1); /* or s2 */
}
len1 = strlen (s1);
len2 = strlen (s2);
minLen = (len1 <= len2)? len1:len2;
shortPtr = (len1 <= len2)? s1:s2;
longPtr = (shortPtr == s1)? s2:s1;
/* Loop through the shorter string */
while (*shortPtr != '\0') {
if (*shortPtr == *longPtr) {
count++;
}
shortPtr++;
longPtr++;
}
return count;
}
int main()
{
char *s1 = "saac";
char *s2 = "sbab";
printf ("Matching len = %d\n", GetMatchingChars (s1,s2));
}
关于比较两个字符串并查找不匹配计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34491872/