C Reference String Operation: strncmp()

The function strncmp() compares one string with another string up-to n characters.

Usage:

int strncmp( const char * target, const char * source, size_t count);

If the two strings are equal then zero is returned. If the target string is less than source then a value that is less then zero is returned.
If the target string is greater than source then a value that is greater then zero is returned.

strncmp() source code example:


	#include<stdio.h>
	#include<string.h>
	
	main()
	{
		char line[100];
		char line2[100];

		printf("Input first word:");
		scanf("%s", line);

		printf("Input second word:");
		scanf("%s", line2);

		if (strncmp(line, line2, 2) == 0)
			printf ("equal\n");

		if (strncmp(line, line2, 2) < 0)
			printf("less then equal\n");

		if (strncmp(line, line2, 2) > 0)\
			printf("greater then equal\n");
	}

Output of the strncmp example:


	Input first word:aabb
	Input second word:aabb
	equal

	Input first word:aaaa
	Input second word:aabb
	equal

Note: the count is set to 2 in this example.

This entry was posted in C Reference string.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 2 responses to “C Reference String Operation: strncmp()”

Why not let us know what you think by adding your own comment!

  1. Puddin Tame on September 24th, 2009:

    Title says strncmp, but discussion and code are for strncat.

  2. admin on September 25th, 2009:

    Sorry about that. I think something went wrong during conversion to wordpress. Fixed the problem.