Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 比较具有不同长度且不带空终止符的2个字符*_C_Compare_String Length - Fatal编程技术网

C 比较具有不同长度且不带空终止符的2个字符*

C 比较具有不同长度且不带空终止符的2个字符*,c,compare,string-length,C,Compare,String Length,我试图比较两个长度不同的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 r

我试图比较两个长度不同的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

}

您可以使用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;
}
int strcmpNoTerminator(常量字符*str1,常量字符*str2,大小字符串,大小字符串){
//获取较短字符串的长度
尺寸长度=str1len

请注意,这是因为您的char*s实际上不是以null结尾的。在示例代码中,
one
two
three
以null结尾。我假设你的问题本身是正确的,而不是你的例子。如果示例是正确的,那么您的char*s以null结尾,您的问题在其他地方,在这种情况下,我们需要查看更多代码以提供帮助。

char*c=“…”
格式不正确。字符串文字的类型为
const char*
。您到底想做什么?示例中的stings确实有空终止符(它们在字符串文本中是隐式的)。你确定在你的真实代码中字符串真的没有空终止符吗?@sth当我执行strcmp时,我得到一个分段错误:11。我在某个地方读到,这意味着我的char*没有空终止符segfault可能有很多原因。确定它发生的确切位置(调试器会告诉您),并发布与有问题的代码行相关的代码。这应该算为字符串吗?因为那时你接受了一个糟糕的答案…为什么这是错误的?他说没有空终止符,
\0
s不应该成为问题。即使有空终止符,也应该可以。唯一的问题是字符串中是否有随机的
\0
s。这似乎是一个合理的假设,但由于问题没有具体说明,我将添加一些内容。很抱歉在我的第一条注释中没有使用正确的字符文字,因此消除了所有歧义。无论如何,将其更改为
memcmp
,一切正常。在这种情况下可能会有所帮助:如果您给出显式长度,您可以初始化
char
数组,而不使用0-终止符,例如
char foo[3]=“foo”。这可能更容易与
sizeof
结合使用,因为您不必减去1来获得实际大小(而且您还保存了一个字节,是的)。当
str1len!=str2len