比较两个字符串并查找不匹配计数

标签 c string

我想比较字符串,每个字符与所有其他字符,无论它们位于相同位置还是在另一个位置具有相同的数字。

我不知道如何正确使用字符串比较,我尝试过 forwhile循环 count但我不知道。

我的问题是这样的。例如。 我的密码是1234。 我的测试是1234。 在这种情况下,我有 4 人死亡。因为数字的位置是一样的。但在这种情况下。 我的密码是1234。 我的测试是1243。 我有 2 人死亡,因为 1 和 2 处于正确位置,但 4 和 3 处于其他位置,但它们位于另一串中。 在这种情况下,我有 2 人死亡和 2 人受伤。 抱歉我的英语不太好。感谢您的帮助..

enter image description here

最佳答案

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/

相关文章:

c - 多次调用 char[] 立即返回函数 fprint

JavaScript include() 并忽略空白,修复代码格式

c# - 在 JavaScript 中,什么等效于 C# 的 @ 语言功能,用于忽略字符串文字中的转义字符?

字符数组比较和 while 循环在 C 中无法正常工作

c - | (或者C语言中的正则表达式中运算符不起作用)

c - 读取一个文件并写入另一个 C

c++ - C++ 字符串中会发生缓冲区溢出吗?

javascript - JS中的字符串到对象

ruby - 如何将 fixnum 添加到 ruby​​ 中的字符串?

c - 如何解析来自MCU UART的不确定长度数据包?