关于字符串、空字符和strcmp

问题描述 投票:0回答:2

我在微控制器中创建了 C 程序,并且想将我的 C 程序中的字符串与从我的 PC 接收的字符串进行比较,我的程序在 PC 中使用 C#,默认情况下 C# 中的字符串不包含空字符。

所以,我的 C 程序不会自动在从 PC 接收的字符串中添加空字符?

strcmp 函数是否可以比较 2 个字符串,一个字符串包含空字符,另一个字符串不包含空字符?

c strcmp null-terminated c-strings
2个回答
0
投票

C 中字符串的定义(来自维基百科)是

字符串是一个连续的代码单元序列,由 第一个零代码(对应于 ASCII 空字符)。

就是说,如果没有 NUL 字符,您将无法使用像

strcmp()
strcpy()
这样的标准字符串函数,最终可能会破坏内存。

你可以做两件事: 在传输之前在 C# 代码的字符串末尾添加

Char.MinValue

string str = "Hello,World!" + Char.MinValue; // Add NUL
.

或者你可以像这样编写自己的字符串比较函数

int myStrcmp(char* str1, char* str2, int len)
{
    int retVal = 0,

    for(int loopcnt = 0; loopcnt < len; loopcnt++)
     {

          if((*str1) > (*str2))
           {
              retVal = -1;
               break;        
           }
          else if((*str1) < (*str2))
           {
              retVal = 1;
               break;                      
           }
           str1++;
           str2++;

     }
 return retVal;
}

但是,您将需要字符串的长度。如果您已经知道长度,那么手动添加 NUL 字符会更好更快。 :-)


0
投票

假设您有一个以 null 结尾的字符串

const char *s1
和另一个字符串
const char *s2
(不一定以 null 结尾)和第二个字符串的长度
unsigned len2
,您可以执行以下操作以获得结果类似于
strcmp()
:

    int result;
    unsigned len1 = strlen(s1);
    result = memcmp(s1, s2, (len1<len2) ? len1 : len2);
    if(result == 0 && len1 < len2) result = -1;
    if(result == 0 && len2 < len1) result = 1;
© www.soinside.com 2019 - 2024. All rights reserved.