C 将固定大小的 char 数组与 String 进行比较

标签 c

我在一个低级嵌入式系统上比较一个固定大小的字符缓冲区和一个简单的字符串。缓冲区比字符串大得多,所以我认为这就是比较运算符说两者不相等的原因。这促使我编写一个简单的函数来将字符串与缓冲区的开头进行比较——这是一个优雅的解决方案吗?谢谢

int CompareString(const char* string, int strlen)
{
     //first check to see if the length is the same
     //if there is a null char at string length then
     //they are equal
     if(MsgBuffer[strlen] != '\0')
     {
         return 0; //they are not equal
     }

     strlen = strlen - 1;

     while(strlen > -1)
     {
         if(string[strlen] != MsgBuffer[strlen])
         {
              return 0; //they are equal
         }

         strlen = strlen - 1;
     }

     return 1; //they are equal
}

最佳答案

通常,您可以考虑使用最大长度为固定缓冲区大小的 strncmp

但您可能在某些方面受到限制,特别是考虑到您在嵌入式环境中操作。它也可能不适合比较空格填充的字符串,其中每个字符串末尾都有不同数量的空格(包括像“formaldehyde”这样的字符串没有空格) - strncmp 不适用于比较 "Hello"{'H','e','l','l','o',' ',' ',' '} 如果大小是 8

如果是这样的话,我会看类似下面的内容:

#include <stdio.h>

int compStr (char *s1, char *s2, size_t sz) {
    while (sz != 0) {
        // At end of both strings, equal.
        if ((*s1 == '\0') && (*s2 == '\0')) break;

        // Treat spaces at end and end-string the same.
        if ((*s1 == '\0') && (*s2 == ' ')) { s2++; sz--; continue; }
        if ((*s1 == ' ') && (*s2 == '\0')) { s1++; sz--; continue; }

        // Detect difference otherwise.
        if (*s1 != *s2) return 0;

        s1++; s2++; sz--;
    }
    return 1;
}

int main (void) {
    printf ("%d\n", compStr ("Hello", "Hello", 5));
    printf ("%d\n", compStr ("Hello", "Hello     ", 5));
    printf ("%d\n", compStr ("Hello     ", "Hello", 5));
    printf ("%d\n", compStr ("Hello     ", "Hello ", 5));
    printf ("%d\n", compStr ("HelloX", "Hello", 5));
    printf ("%d\n", compStr ("HelloX", "HelloY", 5));
    printf ("%d\n", compStr ("HelloX", "HelloY", 6));
    return 0;
}

这将匹配末尾有任意数量空格的字符串,直到特定大小,并且具有可以将任意缓冲区传递给它的优势,而不是假设一个是全局区域。


顺便说一句,使用像 strlen 这样的标准库函数作为变量名并不是一个好主意,因为您可能想要这样做。在某些时候,使用标准库。

关于C 将固定大小的 char 数组与 String 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6148469/

相关文章:

c - MPLAB X 中的有效代码和编译器错误

c - 如何从文本文件存储 STDIN

c - 如何在C中读取 "LoadLibrary"?

c - 为什么GCC会生成 "mov 0x8,%edx"指令导致崩溃?

c++ - 这段代码有内存泄漏吗?

c - Malloc 不在 C 中分配内存

c - 零线程进程?

c - 如何从文本文件中读取数据

c - 像 "typedef int (f)(void)"这样带括号的 typedef 是什么意思?它是一个函数原型(prototype)吗?

谁能告诉我这段伪代码在做什么?