What is strncmp()?
The strncmp() function in C compares at most the first n characters of two strings. It is part of the <string.h> library and provides a safer alternative to strcmp() by preventing comparison beyond specified length.
Function Syntax
int strncmp(const char *str1, const char *str2, size_t n);
| Parameter | Description |
|---|---|
str1 | First string to compare |
str2 | Second string to compare |
n | Maximum number of characters to compare |
| Return | Negative, zero, or positive integer |
Return Values
| Return Value | Meaning |
|---|---|
| 0 | Strings are equal for first n characters |
| < 0 (negative) | str1 is less than str2 (first differing char is smaller) |
| > 0 (positive) | str1 is greater than str2 (first differing char is larger) |
Basic Usage
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello World"; char str2[] = "Hello C Programming"; // Compare first 5 characters int result = strncmp(str1, str2, 5); if(result == 0) { printf("First 5 characters are equal\n"); } else { printf("First 5 characters differ\n"); } // Compare first 6 characters result = strncmp(str1, str2, 6); if(result == 0) { printf("First 6 characters are equal\n"); } else { printf("First 6 characters differ\n"); } return 0; } Output:
First 5 characters are equal First 6 characters differ
Comparing Complete Strings
#include <stdio.h> #include <string.h> int main() { char str1[] = "Apple"; char str2[] = "Apple"; char str3[] = "Banana"; char str4[] = "Apricot"; // Compare full strings (use length or large n) if(strncmp(str1, str2, 10) == 0) { printf("str1 and str2 are equal\n"); } // Compare first 2 characters int result = strncmp(str1, str4, 2); printf("Comparing 'Ap' from Apple vs Apricot: %d\n", result); // 0 (equal) // Compare first 3 characters result = strncmp(str1, str4, 3); printf("Comparing 'App' vs 'Apr': %d\n", result); // Negative ('p' < 'r') // Compare strings with different lengths result = strncmp(str2, str3, 5); printf("Apple vs Banana: %d\n", result); // Negative ('A' < 'B') return 0; } Practical Example 1: Case-Insensitive Comparison
#include <stdio.h> #include <string.h> #include <ctype.h> int strnicmp(const char *str1, const char *str2, size_t n) { for(size_t i = 0; i < n; i++) { char c1 = tolower(str1[i]); char c2 = tolower(str2[i]); if(c1 == '\0' && c2 == '\0') return 0; if(c1 != c2) return c1 - c2; } return 0; } int main() { char input[] = "Hello"; char command[] = "HELLO"; // Standard strncmp (case-sensitive) if(strncmp(input, command, 5) == 0) { printf("strncmp: Equal\n"); } else { printf("strncmp: Not equal (case matters)\n"); } // Case-insensitive comparison if(strnicmp(input, command, 5) == 0) { printf("strnicmp: Equal (ignoring case)\n"); } return 0; } Practical Example 2: Input Validation
#include <stdio.h> #include <string.h> int main() { char userInput[100]; char validCommands[][10] = {"HELP", "EXIT", "LIST", "SAVE"}; printf("Enter command: "); fgets(userInput, sizeof(userInput), stdin); // Remove newline userInput[strcspn(userInput, "\n")] = '\0'; // Check each command int found = 0; for(int i = 0; i < 4; i++) { // Compare ignoring case by converting both to uppercase if(strncmp(validCommands[i], userInput, strlen(validCommands[i])) == 0) { printf("Command recognized: %s\n", validCommands[i]); found = 1; break; } } if(!found) { printf("Unknown command\n"); } return 0; } Practical Example 3: File Extension Checker
#include <stdio.h> #include <string.h> int hasExtension(const char *filename, const char *extension) { int len = strlen(filename); int extLen = strlen(extension); if(len < extLen) return 0; // Compare last extLen characters const char *fileExt = filename + len - extLen; return (strncmp(fileExt, extension, extLen) == 0); } int main() { char files[][50] = { "document.txt", "image.jpg", "script.c", "data.csv", "notes.txt" }; printf("Text files (.txt):\n"); for(int i = 0; i < 5; i++) { if(hasExtension(files[i], ".txt")) { printf(" - %s\n", files[i]); } } printf("\nC files (.c):\n"); for(int i = 0; i < 5; i++) { if(hasExtension(files[i], ".c")) { printf(" - %s\n", files[i]); } } return 0; } Output:
Text files (.txt): - document.txt - notes.txt C files (.c): - script.c
Practical Example 4: Prefix Checking
#include <stdio.h> #include <string.h> int startsWith(const char *str, const char *prefix) { return strncmp(str, prefix, strlen(prefix)) == 0; } int endsWith(const char *str, const char *suffix) { int strLen = strlen(str); int suffixLen = strlen(suffix); if(strLen < suffixLen) return 0; return strncmp(str + strLen - suffixLen, suffix, suffixLen) == 0; } int main() { char strings[][50] = { "https://google.com", "http://example.com", "ftp://files.com", "https://github.com" }; printf("URLs starting with 'https':\n"); for(int i = 0; i < 4; i++) { if(startsWith(strings[i], "https")) { printf(" - %s\n", strings[i]); } } printf("\nURLs ending with '.com':\n"); for(int i = 0; i < 4; i++) { if(endsWith(strings[i], ".com")) { printf(" - %s\n", strings[i]); } } return 0; } Output:
URLs starting with 'https': - https://google.com - https://github.com URLs ending with '.com': - https://google.com - http://example.com
strncmp() vs strcmp()
| Feature | strcmp() | strncmp() |
|---|---|---|
| Compares | Entire strings | At most n characters |
| Safety | Less safe (no limit) | Safer (bounds check) |
| Parameters | 2 parameters | 3 parameters |
| Null characters | Stops at '\0' in either string | Stops at '\0' or after n chars |
| Use case | Exact full string match | Prefix check, partial compare |
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello A"; char str2[] = "Hello B"; char str3[] = "Hello World"; // strcmp compares full strings printf("strcmp(Hello A, Hello B): %d\n", strcmp(str1, str2)); printf("strcmp(Hello A, Hello World): %d\n", strcmp(str1, str3)); // strncmp compares only first 6 chars printf("strncmp(Hello A, Hello B, 6): %d\n", strncmp(str1, str2, 6)); printf("strncmp(Hello A, Hello World, 6): %d\n", strncmp(str1, str3, 6)); // Both functions find differences char str4[] = "Hello"; char str5[] = "Hello\0Extra"; printf("strcmp with null: %d\n", strcmp(str4, str5)); // 0 (stops at null) printf("strncmp with null: %d\n", strncmp(str4, str5, 10)); // 0 (stops at null) return 0; } Manual Implementation of strncmp()
#include <stdio.h> int my_strncmp(const char *str1, const char *str2, size_t n) { for(size_t i = 0; i < n; i++) { // If both strings end at same position, they're equal if(str1[i] == '\0' && str2[i] == '\0') { return 0; } // If characters differ, return difference if(str1[i] != str2[i]) { return (unsigned char)str1[i] - (unsigned char)str2[i]; } // If only str1 ends, str1 is less if(str1[i] == '\0') { return -1; } // If only str2 ends, str1 is greater if(str2[i] == '\0') { return 1; } } // All n characters are equal return 0; } int main() { char test1[] = "Hello"; char test2[] = "Hello World"; char test3[] = "Help"; printf("My Implementation:\n"); printf("Compare 'Hello' vs 'Hello World' (5 chars): %d\n", my_strncmp(test1, test2, 5)); // 0 (equal) printf("Compare 'Hello' vs 'Help' (4 chars): %d\n", my_strncmp(test1, test3, 4)); // Positive ('o' vs 'p') printf("Compare 'Hello' vs 'Help' (3 chars): %d\n", my_strncmp(test1, test3, 3)); // 0 ('Hel' vs 'Hel') printf("\nStandard strncmp:\n"); printf("Compare 'Hello' vs 'Hello World' (5 chars): %d\n", strncmp(test1, test2, 5)); printf("Compare 'Hello' vs 'Help' (4 chars): %d\n", strncmp(test1, test3, 4)); printf("Compare 'Hello' vs 'Help' (3 chars): %d\n", strncmp(test1, test3, 3)); return 0; } Checking String Prefixes
#include <stdio.h> #include <string.h> int main() { char strings[][30] = { "apple_fruit.txt", "apple_pie_recipe.txt", "banana_fruit.txt", "apple_sauce.txt" }; printf("All apple-related files:\n"); for(int i = 0; i < 4; i++) { if(strncmp(strings[i], "apple", 5) == 0) { printf(" - %s\n", strings[i]); } } // Check for multiple prefixes printf("\nFruit files:\n"); for(int i = 0; i < 4; i++) { if(strncmp(strings[i], "apple", 5) == 0 || strncmp(strings[i], "banana", 6) == 0) { printf(" - %s\n", strings[i]); } } return 0; } Using strncmp() with User Input
#include <stdio.h> #include <string.h> int main() { char input[100]; char response[10]; printf("Do you want to continue? (yes/no): "); fgets(input, sizeof(input), stdin); // Remove newline input[strcspn(input, "\n")] = '\0'; // Check if user typed 'yes' (case-sensitive) if(strncmp(input, "yes", 3) == 0) { printf("Continuing...\n"); } // Check for 'no' else if(strncmp(input, "no", 2) == 0) { printf("Exiting...\n"); } // Check for 'y' or 'n' shortcuts else if(strncmp(input, "y", 1) == 0) { printf("Continuing (shortcut)...\n"); } else if(strncmp(input, "n", 1) == 0) { printf("Exiting (shortcut)...\n"); } else { printf("Invalid input\n"); } return 0; } Common Mistakes
#include <stdio.h> #include <string.h> int main() { // MISTAKE 1: Mixing up parameter order char str1[] = "Apple"; char str2[] = "Banana"; // WRONG: Order matters int result = strncmp(str2, str1, 3); // Compares Banana vs Apple // CORRECT: strncmp(str1, str2, n) if(strncmp(str1, str2, 3) < 0) { printf("'Apple' < 'Banana'\n"); } // MISTAKE 2: Using negative n (size_t is unsigned) // strncmp(str1, str2, -1); // WRONG! Causes large positive number // MISTAKE 3: Assuming strncmp returns only -1, 0, 1 int cmp = strncmp("ABC", "ABD", 3); printf("Comparison result: %d\n", cmp); // Might be -1, -100, etc. // Fixed: Check sign, not specific value if(cmp < 0) { printf("'ABC' is less than 'ABD'\n"); } // MISTAKE 4: Not handling null terminators properly char text[] = "Hello"; char prefix[] = "HelloWorld"; // Compares only 'Hello' (stops at null in text) if(strncmp(text, prefix, 10) == 0) { printf("Equal within 10 chars (stops at null)\n"); } return 0; } Performance Comparison
#include <stdio.h> #include <string.h> #include <time.h> int main() { char str1[] = "The quick brown fox jumps over the lazy dog"; char str2[] = "The quick brown fox jumps over the lazy cat"; clock_t start, end; double cpu_time; // Compare full string start = clock(); for(int i = 0; i < 1000000; i++) { strcmp(str1, str2); } end = clock(); printf("strcmp (full): %.3f seconds\n", (double)(end - start) / CLOCKS_PER_SEC); // Compare only first 20 chars start = clock(); for(int i = 0; i < 1000000; i++) { strncmp(str1, str2, 20); } end = clock(); printf("strncmp (20 chars): %.3f seconds\n", (double)(end - start) / CLOCKS_PER_SEC); // Compare only first 5 chars start = clock(); for(int i = 0; i < 1000000; i++) { strncmp(str1, str2, 5); } end = clock(); printf("strncmp (5 chars): %.3f seconds\n", (double)(end - start) / CLOCKS_PER_SEC); return 0; } Quick Reference Table
| Scenario | Code Example | Use Case |
|---|---|---|
| Exact full match | strncmp(a, b, strlen(a) + 1) | Full string comparison |
| Prefix check | strncmp(str, prefix, strlen(prefix)) == 0 | Check if string starts with prefix |
| First n chars | strncmp(a, b, n) == 0 | Compare only first n characters |
| Case-insensitive | Custom function using tolower() | Ignore case differences |
| File extension | strncmp(filename + len - 3, ".txt", 3) | Check file type |
| User command | strncmp(input, "exit", 4) == 0 | Partial command matching |
Summary
strncmp()compares at most n characters of two strings- Returns 0 if first n characters are equal
- Returns negative if str1 < str2
- Returns positive if str1 > str2
- Safer than strcmp() for bounded comparison
- Useful for prefix checking and input validation
- Stops at null terminator even before n characters
- n should be less than or equal to buffer sizes
- Include
<string.h>header file - Returns difference of ASCII values at first mismatch
Complete C Programming Guide + Compilers Collection
1. C srand() Function – Understanding Seed Initialization
https://macronepal.com/understanding-the-c-srand-function
Explains how srand() initializes the pseudo-random number generator in C by setting a seed value. Using the same seed produces the same sequence, while time(NULL) gives different results each run.
2. C rand() Function Mechanics and Limitations
https://macronepal.com/c-rand-function-mechanics-and-limitations
Explains how rand() generates pseudo-random numbers between 0 and RAND_MAX, its deterministic nature, and limitations for security use cases.
3. C log() Function
https://macronepal.com/c-log-function-2
Covers natural logarithm calculation using <math.h> and its applications.
4. Mastering Date and Time in C
https://macronepal.com/mastering-date-and-time-in-c
Explains <time.h> functions like time(), clock(), difftime(), and struct tm.
5. Mastering time_t Type in C
https://macronepal.com/mastering-the-c-time_t-type-for-time-management
Explains time representation as seconds since Unix epoch and conversion functions.
6. C exp() Function
https://macronepal.com/c-exp-function-mechanics-and-implementation
Explains exponential function exp(x) and its scientific applications.
7. C log() Function (Alternate Guide)
https://macronepal.com/c-log-function
Comparison of log() and log10() with usage examples.
8. C log10() Function
https://macronepal.com/mastering-the-log10-function-in-c
Explains base-10 logarithm for engineering and scientific applications.
9. C tan() Function
https://macronepal.com/understanding-the-c-tan-function
Explains tangent function and radian-based calculations.
10. Random Numbers in C (Secure vs Predictable)
https://macronepal.com/mastering-c-random-numbers-for-secure-and-predictable-applications
Explains difference between rand() and secure randomness methods.
11. Free Online C Compiler
https://macronepal.com/free-online-c-code-compiler-2
Browser-based compiler for testing C programs instantly.
C Functions, Arguments, Parameters & Flow
Mastering Functions in C – Complete Guide
https://macronepal.com/c/mastering-functions-in-c-a-complete-guide/
Covers function structure, modular programming, and real-world usage.
Function Arguments in C
https://macronepal.com/c-function-arguments/
Explains how arguments are passed and used in function calls.
Function Parameters in C
https://macronepal.com/c-function-parameters/
Explains defining inputs for functions and matching them with arguments.
Function Declarations in C
https://macronepal.com/c-function-declarations-syntax-rules-and-best-practices/
Covers prototypes, syntax rules, and best practices.
Function Calls in C
https://macronepal.com/understanding-function-calls-in-c-syntax-mechanics-and-best-practices/
Explains execution flow and parameter handling during function calls.
Void Functions in C
https://macronepal.com/understanding-void-functions-in-c-syntax-patterns-and-best-practices/
Explains functions that do not return values.
Return Values in C
https://macronepal.com/c-return-values-mechanics-types-and-best-practices/
Explains different return types and how functions return results.
Pass-by-Value in C
https://macronepal.com/aws/understanding-pass-by-value-in-c-mechanics-implications-and-best-practices/
Explains how copies of variables are passed into functions.
Pass-by-Reference in C
https://macronepal.com/c/understanding-pass-by-reference-in-c-pointers-semantics-and-safe-practices/
Explains using pointers to modify original variables.
C strstr() Function
https://macronepal.com/aws/c-strstr-function/
Explains substring search inside strings in C.
C Preprocessor & Macros
https://macronepal.com/mastering-c-variadic-macros-for-flexible-debugging/
https://macronepal.com/mastering-the-stdc-macro-in-c/
https://macronepal.com/c-time-macro-mechanics-and-usage/
https://macronepal.com/understanding-the-c-date-macro/
https://macronepal.com/c-file-type/
https://macronepal.com/mastering-c-line-macro-for-debugging-and-diagnostics/
https://macronepal.com/mastering-predefined-macros-in-c/
https://macronepal.com/c-error-directive-mechanics-and-usage/
https://macronepal.com/understanding-the-c-pragma-directive/
https://macronepal.com/c-include-directive/
C Structures, Memory, Scope & Linkage
https://macronepal.com/mastering-structures-in-c/
https://macronepal.com/c-structure-declaration-mechanics-and-usage/
https://macronepal.com/c-structure-initialization-mechanics-and-best-practices/
https://macronepal.com/mastering-c-structure-member-access-for-reliable-data-handling/
https://macronepal.com/c-nested-structures/
https://macronepal.com/mastering-arrays-of-structures-in-c/
https://macronepal.com/c-structure-pointers-mechanics-and-implementation/
https://macronepal.com/understanding-c-structure-parameter-passing-mechanics/
https://macronepal.com/mastering-c-returning-structures-for-efficient-data-flow/
https://macronepal.com/c-self-referential-structures/
https://macronepal.com/mastering-structure-alignment-in-c/
https://macronepal.com/c-structure-padding-mechanics-and-optimization/
https://macronepal.com/understanding-c-flexible-array-members-mechanics-and-usage/
https://macronepal.com/mastering-c-anonymous-structures-for-flattened-data-layouts/
https://macronepal.com/c-unions/
https://macronepal.com/mastering-c-name-mangling-and-symbol-decoration/
https://macronepal.com/c-no-linkage-mechanics-and-scope-isolation/
https://macronepal.com/understanding-c-internal-linkage-mechanics-and-architecture/
C Scope, Storage Classes & Typedef
https://macronepal.com/mastering-function-prototype-scope-in-c/
https://macronepal.com/c-function-scope-mechanics-and-visibility/
https://macronepal.com/understanding-c-file-scope-mechanics-and-architecture/
https://macronepal.com/mastering-c-scope-rules-for-predictable-name-resolution/
https://macronepal.com/c-scope-rules/
https://macronepal.com/mastering-c-register-storage-class-for-historical-context-and-modern-alternatives/
https://macronepal.com/mastering-_thread_local-in-c/
https://macronepal.com/c-extern-storage-class-mechanics-and-usage/
https://macronepal.com/understanding-the-c-static-storage-class-mechanics-and-usage/
https://macronepal.com/c-auto-storage-class/
https://macronepal.com/c-typedef-with-pointers/
Extra Articles
https://macronepal.com/13757-2/
https://macronepal.com/13748-2/
https://macronepal.com/13747-2/
https://macronepal.com/13746-2/
https://macronepal.com/13745-2/
https://macronepal.com/13708-2/
https://macronepal.com/13707-2/
https://macronepal.com/13702-2/
Online Compilers
https://macronepal.com/free-html-online-code-compiler/
https://macronepal.com/free-online-python-code-compiler/
https://macronepal.com/free-online-python2-code-compiler/
https://macronepal.com/free-online-java-code-compiler/
https://macronepal.com/free-online-javascript-code-compiler/
https://macronepal.com/free-online-node-js-code-compiler/
https://macronepal.com/free-online-c-code-compiler/
https://macronepal.com/free-online-c-code-compiler-2/
https://macronepal.com/free-online-c-code-compiler-3/
https://macronepal.com/free-online-php-code-compiler/
https://macronepal.com/free-online-ruby-code-compiler/
https://macronepal.com/free-online-perl-code-compiler/
https://macronepal.com/free-online-lua-code-compiler/
https://macronepal.com/free-online-tcl-code-compiler/
https://macronepal.com/free-online-groovy-code-compiler/
https://macronepal.com/free-online-j-shell-code-compiler/
https://macronepal.com/free-online-haskell-code-compiler/
https://macronepal.com/free-online-scala-code-compiler/
https://macronepal.com/free-online-common-lisp-code-compiler/
https://macronepal.com/free-online-d-code-compiler/
https://macronepal.com/free-online-ada-code-compiler/
https://macronepal.com/free-erlang-code-compiler/
https://macronepal.com/free-online-assembly-code-compiler/
Complete Guide to Core & Advanced C Programming Concepts (Functions, Strings, Arrays, Loops, I/O, Control Flow)
https://macronepal.com/bash/building-blocks-of-c-a-complete-guide-to-functions/
Explains how functions in C work as reusable blocks of code, including declaration, definition, parameters, return values, and modular programming structure.
https://macronepal.com/bash/the-heart-of-text-processing-a-complete-guide-to-strings-in-c-2/
Explains how strings are handled in C using character arrays, string manipulation techniques, and common library functions for text processing.
https://macronepal.com/bash/the-cornerstone-of-data-organization-a-complete-guide-to-arrays-in-c/
Explains arrays in C as structured memory storage for multiple values, including indexing, initialization, and efficient data organization.
https://macronepal.com/bash/guaranteed-execution-a-complete-guide-to-the-do-while-loop-in-c/
Explains the do-while loop in C, where the loop body executes at least once before checking the condition.
https://macronepal.com/bash/mastering-iteration-a-complete-guide-to-the-for-loop-in-c/
Explains the for loop in C, including initialization, condition checking, and increment/decrement for controlled iteration.
https://macronepal.com/bash/mastering-iteration-a-complete-guide-to-while-loops-in-c/
Explains the while loop in C, focusing on condition-based repetition and proper loop control mechanisms.
https://macronepal.com/bash/beyond-if-else-a-complete-guide-to-switch-case-in-c/
Explains switch-case statements in C, enabling multi-branch decision-making based on variable values.
https://macronepal.com/bash/mastering-conditional-logic-a-complete-guide-to-if-else-statements-in-c/
Explains if-else statements in C for decision-making and controlling program flow based on conditions.
https://macronepal.com/bash/mastering-the-fundamentals-a-complete-guide-to-arithmetic-operations-in-c/
Explains arithmetic operations in C such as addition, subtraction, multiplication, division, and operator precedence.
https://macronepal.com/bash/foundation-of-c-programming-a-complete-guide-to-basic-input-output/
Explains basic input and output in C using scanf and printf for interacting with users and displaying results.
Online C Code Compiler
https://macronepal.com/free-online-c-code-compiler-2/
