C strncmp Function

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);
ParameterDescription
str1First string to compare
str2Second string to compare
nMaximum number of characters to compare
ReturnNegative, zero, or positive integer

Return Values

Return ValueMeaning
0Strings 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()

Featurestrcmp()strncmp()
ComparesEntire stringsAt most n characters
SafetyLess safe (no limit)Safer (bounds check)
Parameters2 parameters3 parameters
Null charactersStops at '\0' in either stringStops at '\0' or after n chars
Use caseExact full string matchPrefix 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

ScenarioCode ExampleUse Case
Exact full matchstrncmp(a, b, strlen(a) + 1)Full string comparison
Prefix checkstrncmp(str, prefix, strlen(prefix)) == 0Check if string starts with prefix
First n charsstrncmp(a, b, n) == 0Compare only first n characters
Case-insensitiveCustom function using tolower()Ignore case differences
File extensionstrncmp(filename + len - 3, ".txt", 3)Check file type
User commandstrncmp(input, "exit", 4) == 0Partial 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 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/

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper