C Online Compiler
Example: String Comparison in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// String Comparison #include <stdio.h> #include <string.h> // Required for strcmp() int main() { // Step 1: Declare multiple strings for comparison char str1[] = "apple"; char str2[] = "apple"; char str3[] = "banana"; char str4[] = "apply"; int result; // Step 2: Compare str1 and str2 (identical) result = strcmp(str1, str2); printf("Comparing \"%s\" and \"%s\": Result = %d (Expected 0)\n", str1, str2, result); // Step 3: Compare str1 and str3 (str1 < str3) result = strcmp(str1, str3); printf("Comparing \"%s\" and \"%s\": Result = %d (Expected negative)\n", str1, str3, result); // Step 4: Compare str3 and str1 (str3 > str1) result = strcmp(str3, str1); printf("Comparing \"%s\" and \"%s\": Result = %d (Expected positive)\n", str3, str1, result); // Step 5: Compare str1 and str4 (str1 < str4) result = strcmp(str1, str4); printf("Comparing \"%s\" and \"%s\": Result = %d (Expected negative)\n", str1, str4, result); // Example with strncmp (compare first 'n' characters) char password_stored[] = "secret123"; char password_input[] = "secret12345"; // Compare only the first 9 characters result = strncmp(password_stored, password_input, 9); printf("\nComparing first 9 chars of \"%s\" and \"%s\": Result = %d (Expected 0)\n", password_stored, password_input, result); return 0; }
Output
Clear
ADVERTISEMENTS