9

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

char *str1 = "hello";
char *str2 = "world";
//compare str1 and str2 ?
1
  • 8
    Those should be const char *. Commented Sep 8, 2010 at 0:23

3 Answers 3

13

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'.
Sign up to request clarification or add additional context in comments.

1 Comment

+1, but I wouldn't link to that page, it uses the horrible outdated gets function in its example, which is definitely not a good idea for someone beginning C. The POSIX page is an alternative.
5
if ( strcmp( str1, str2 ) == 0 )
  same

Comments

1

You can compare two char*s using the strcmp function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.