簡體   English   中英

將以null結尾的字符串與C中的非空終止字符串進行比較

[英]Comparing null-terminated string with a non null-terminated string in C

我正在使用的反序列化庫(messagepack)不提供以null結尾的字符串。 相反,我得到一個指向字符串開頭和長度的指針。 將此字符串與普通的以null結尾的字符串進行比較的最快方法是什么?

最快的方法是strncmp() ,它限制了要比較的長度。

 if (strncmp(sa, sb, length)==0)  
    ...

但是,假設您使用的長度是兩個字符串的最大長度。 如果以null結尾的字符串可以具有更大的長度,則首先必須比較長度。

 if(strncmp(sa,sb, length)==0 && strlen(sa)<=length) // sa being the null terminated one
     ...

請注意,在比較之后有意檢查strlen(),以避免在第一個caracters不匹配時不必要地迭代空終止字符串的所有字符。

最后一個變體是:

 if(strncmp(sa,sb, length)==0 && sa[length]==0) // sa being the null terminated one
     ...
int compare(char *one, size_t onelen, char *two, size_t twolen)
{
int dif;

  dif = memcmp(one, two, onelen < twolen ? onelen : twolen);
  if (dif) return dif;

  if (onelen == twolen) return 0;
  return onelen > twolen? 1 : -1;
}

用法:

...
int result;
char einz[4] = "einz"; // not terminated
char *zwei = "einz";   // terminated

result = compare(einz, sizeof einz, zwei, strlen(zwei));

...

這是一種方式:

bool is_same_string(char const *s1, char const *s2, size_t s2_len)
{
    char const *s2_end = s2 + s2_len;
    for (;;)
    {
        if ( s1[0] == 0 || s2 == s2_end )
            return s1[0] == 0 && s2 == s2_end;

        if ( *s1++ != *s2++ )
            return false;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM