Comparing Strings
Deslize para mostrar o menu
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
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
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.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo