如何在C语言中比较指向字符串的指针

9
如何在C语言中比较两个字符串?帮我一下,我是初学者@@
char *str1 = "hello";
char *str2 = "world";
//compare str1 and str2 ?

8
这些应该是“const char *”。 - dreamlax
3个回答

13

您可能希望使用strcmp函数:

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    int v;
    const char *str1 = "hello";
    const char *str2 = "world";

    v = strcmp(str1, str2);

    if (v < 0)
        printf("'%s' is less than '%s'.\n", str1, str2);
    else if (v == 0)
        printf("'%s' equals '%s'.\n", str1, str2);
    else if (v > 0)
        printf("'%s' is greater than '%s'.\n", str1, str2);

    return 0;
}

结果:

'hello' is less than 'world'.

+1,但我不会链接到那个页面,因为它在示例中使用可怕且过时的 gets 函数,对于初学C语言的人绝对不是一个好主意。POSIX页面是一个替代选择。 - dreamlax

5
if ( strcmp( str1, str2 ) == 0 )
  same

1

您可以使用 strcmp function 函数来比较两个 char*


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接