【问题标题】:comparing 2 char* with different lengths without null terminators比较 2 char* 具有不同长度而没有空终止符
【发布时间】:2014-07-16 01:13:18
【问题描述】:

我正在尝试比较两个不同长度的 char* 的字符串文字值。他们没有空终止符,所以我不能使用 strcmp。我应该如何确定它们是否相等?有什么方法可以用吗?

示例代码:

int main(){
    char* one = "milk";
    char* two = "dalek! Exterminate!";
    char* three = "milk";

    //Compare and check to see if they are equal. one and two would return false but one and three would return true

}

【问题讨论】:

  • char* c = "..." 格式不正确。字符串文字的类型为const char*。你/究竟/想要做什么?
  • 您的示例 do 中的字符串具有空终止符(它们隐含在字符串文字中)。您确定在您的真实代码中字符串真的没有空终止符吗?
  • @sth 当我执行 strcmp 时,我得到一个分段错误:11。我在某处读到这意味着我的 char* 没有空终止符
  • 段错误可能有很多原因。确定它到底发生在哪里(调试器会告诉你)并发布与有问题的代码行相关的代码。
  • 应该算字符串吗?因为那时你接受了一个错误的答案......

标签: c compare string-length


【解决方案1】:

您可以使用 memcmp 比较字符串,直到其中一个结束。

int strcmpNoTerminator ( const char * str1, const char * str2, size_t str1len, size_t str2len ) {
    // Get the length of the shorter string
    size_t len = str1len < str2len ? str1len : str2len;
    // Compare the strings up until one ends
    int cmp = memcmp(str1, str2, len);
    // If they weren't equal, we've got our result
    // If they are equal and the same length, they matched
    if(cmp != 0 || str1len == str2len) {
        return cmp;
    }
    // If they were equal but one continues on, the shorter string is 
    // lexicographically smaller
    return str1len < str2len ? -1 : 1;
}

请注意,这是如果您的 char *s 实际上不是以 null 结尾的。在您的示例代码中,onetwothree 以空值结尾。我假设您的问题本身是正确的,而不是您的示例。如果示例正确,则您的 char *s 以 null 结尾,而您的问题出在其他地方,在这种情况下,我们需要查看更多代码来提供帮助。

【讨论】:

  • 为什么这是错误的?他说没有空终止符,\0s 应该不是问题。即使有空终止符,这也应该没问题。这应该是一个问题的唯一情况是是否有随机的\0s 散落在整个字符串中。
  • 似乎是一个公平的假设,但由于问题没有具体说明,我将为其添加一些内容。
  • 很抱歉在我的第一条评论中没有使用正确的字符文字,因此消除了所有歧义。反正改成memcmp就好了。
  • 在这种情况下可能会有所帮助:如果您给出明确的长度,您可以在没有 0 终止符的情况下初始化 char arrays,例如char foo[3] = "foo";。这可能更容易与 sizeof 结合使用,因为您不必减去 1 即可获得实际大小(并且您节省了一个字节,是的)。
  • str1len != str2len 时先进行长度相等检查并完全避免 memcmp 调用不是更有意义吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多