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