What does strcmp return if two similar strings are of different lengths?

后端 未结 5 1294
庸人自扰
庸人自扰 2021-02-19 15:09

I understand that if you have \'cat\' (string1) and \'dog\' (string2) in strcmp (this is a C question) then the return value of strcmp would be less than 0 (since \'cat\' is lex

5条回答
  •  一向
    一向 (楼主)
    2021-02-19 15:45

    If you want to compare just the initial len characters of two strings, use strncmp instead of strcmp:

    #include 
    size_t len = 3;
    int res = strncmp("dog", "dog2", len);
    

    res will be 0 in this case.

提交回复
热议问题