Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Comparing Strings | Common String Operations
C Strings

bookComparing Strings

Veeg om het menu te tonen

Comparing strings in C is a common task, whether you need to check if two strings are exactly the same or determine their order alphabetically. The standard library provides functions for these purposes: strcmp and strncmp. The strcmp function compares two strings character by character until it finds a difference or reaches the end of both strings. If all characters are the same and both strings end together, the strings are considered equal. The strncmp function works similarly but only compares up to a specified number of characters. This is useful when you want to compare prefixes or only part of a string.

compare_strings.c

compare_strings.c

copy
1234567891011121314151617
#include <stdio.h> #include <string.h> int main() { char str1[] = "apple"; char str2[] = "apricot"; int result = strcmp(str1, str2); if (result == 0) printf("The strings are equal.\n"); else if (result < 0) printf("\"%s\" comes before \"%s\".\n", str1, str2); else printf("\"%s\" comes after \"%s\".\n", str1, str2); return 0; }

In this code sample, you see how strcmp is used to compare two strings: str1 and str2. The function returns an integer: zero if the strings are equal, a negative value if the first string comes before the second, and a positive value if the first string comes after the second. These results are based on the lexicographical order, which is similar to dictionary order and depends on the ASCII values of the characters. The program prints a message based on the comparison result, helping you understand how the output changes depending on the input strings.

partial_compare.c

partial_compare.c

copy
123456789101112131415
#include <stdio.h> #include <string.h> int main() { char str1[] = "banana"; char str2[] = "bandana"; int result = strncmp(str1, str2, 3); if (result == 0) printf("The first 3 characters are equal.\n"); else printf("The first 3 characters are different.\n"); return 0; }

You should use strncmp instead of strcmp when you only care about part of a string, such as checking if two strings share a common prefix or if the first few characters match. In the previous code sample, strncmp(str1, str2, 3) compares only the first three characters of "banana" and "bandana". This is helpful when you want to ignore the rest of the string and focus on a certain portion. On the other hand, use strcmp when you need to compare entire strings for equality or order.

question mark

What does strcmp return when two strings are equal?

Select the correct answer

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 3. Hoofdstuk 3
some-alt