0
0
Cprogramming~5 mins

String comparison

Choose your learning style9 modes available
Introduction
We compare strings to check if two words or sentences are the same or to find which one comes first in order.
Checking if a username matches a stored name.
Sorting a list of words alphabetically.
Finding if a password entered matches the saved password.
Comparing two text inputs to see if they are equal.
Syntax
C
#include <string.h>

int strcmp(const char *str1, const char *str2);
strcmp returns 0 if the strings are exactly the same.
If the first string is 'less' than the second, strcmp returns a negative number; if 'greater', a positive number.
Examples
This compares two identical strings and result will be 0.
C
#include <string.h>

int result = strcmp("apple", "apple");
Since "apple" comes before "banana", result will be negative.
C
int result = strcmp("apple", "banana");
Since "banana" comes after "apple", result will be positive.
C
int result = strcmp("banana", "apple");
Sample Program
This program compares two pairs of strings and prints the results and their order.
C
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "hello";
    char str2[] = "hello";
    char str3[] = "world";

    int res1 = strcmp(str1, str2);
    int res2 = strcmp(str1, str3);

    printf("Compare str1 and str2: %d\n", res1);
    printf("Compare str1 and str3: %d\n", res2);

    if (res1 == 0) {
        printf("str1 and str2 are the same.\n");
    } else {
        printf("str1 and str2 are different.\n");
    }

    if (res2 < 0) {
        printf("str1 comes before str3.\n");
    } else if (res2 > 0) {
        printf("str1 comes after str3.\n");
    } else {
        printf("str1 and str3 are the same.\n");
    }

    return 0;
}
OutputSuccess
Important Notes
Always include to use strcmp.
strcmp compares strings letter by letter using ASCII values.
Do not use == to compare strings in C; it compares addresses, not content.
Summary
Use strcmp to compare two strings in C.
strcmp returns 0 if strings are equal, negative if first is less, positive if first is greater.
Always include and do not use == for string content comparison.