Ads by ProfitSence
Close

How to Compare Strings in C ?

Last Updated on Wednesday 5th Oct 2022

c strings compare

You can't (usefully) compare strings using != or ==, you need to use strcmp.

Use strcmp

			
					while (strcmp(check,input) != 0)

			
	

or

			
					while (!strcmp(check,input))

			
	

Compare Strings

			
					#include <stdio.h>

int compareStrings(const char *s1, const char *s2) {
    int i = 0, answer;
    while (*s1 == *s2 && *s1 != '\0' && *s2 != '\0') {
        s1++;
        s2++;
        // printf("%s\n%s\n\n", s1, s2);
    }

    if (*s1 < *s2)
        answer = -1;
    else if (*s1 == *s2)
        answer = 0;
    else
        answer = 1;

    return answer;
}

int main (void) {
    const char s1[30] = "Hello World";
    const char s2[30] = "Hello World";
    int j = compareStrings(s1, s2);
    printf("%i\n", j);

    return 0;
}

			
	

The Above Code returns 0

			
					int main (void) {
    const char s1[30] = "Hello";
    const char s2[30] = "Hello World";
    int k = compareStrings(s1, s2);
    printf("%i\n", k);

    return 0;
}

			
	

The Above Code returns -1