Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare pointer to strings in C

Tags:

c

how to compare two strings in C? Help me, I am beginner@@

char *str1 = "hello";
char *str2 = "world";
//compare str1 and str2 ?
like image 789
Rn2dy Avatar asked Sep 08 '10 00:09

Rn2dy


2 Answers

You may want to use 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;
}

Result:

'hello' is less than 'world'.
like image 85
Daniel Vassallo Avatar answered Sep 28 '22 18:09

Daniel Vassallo


if ( strcmp( str1, str2 ) == 0 )
  same
like image 38
AndersK Avatar answered Sep 28 '22 18:09

AndersK