Sunday, 8 December 2013

How to Compare Two Strings in C Programming

The string that is smaller is lexicographically smaller (it starts with letters that are before the starting letters of the other string in a dictionary).


1.Include the string library in your program. This library contains a lot of useful functions used when working with strings, including one that compares them. Place the following code at the top of the program, with the other includes.
include <string.h>


2.Declare the string variables. Those will be the strings you will compare. Note that strings in C are declared as arrays of characters, not as a special string type.
char string1[limit], string2[limit];
// Replace "limit" with the maximum length of the strings

3.Decide how many characters you wish to compare.
  • The more you compare, the higher precision you will achieve (For example, if the strings were "Hell" and "Hello" and you compared four characters, they would appear the same).
  • If you compare a lot of characters, the comparison will be slower.
  • There is no need to make this number greater than the strings' lengths (there are no characters to compare after their end).
4.Create a variable that contains the number of characters to compare.

int compareLimit = 100;
// Here, the limit is 100. However, you may change it to satisfy your needs.

5.Initialize the strings. You may assign the value manually, read it from the input, read it from a file...

6.Compare the strings. The comparison is done using the strncmp() function, and the returned type is an integer.

int result = strncmp(string1, string2, compareLimit);

7.Examine the result. If it is positive, the first string is larger. If it is negative, the second is larger. If it is 0, they are equal.

if(result > 0)
printf("string1 > string2");
else if(result < 0)
printf("string2 > string1");
else
printf("string1 == string2");

Simple Code
A program that answers simple questions ("What is your name?", "How are you?", "What do you think of 9FAQ?")

#include <stdio.h>
#include <string.h>
 
int main()
{
  printf("Hello! Ask me a question!\n");
  while(1)
  {
    char str[100];
    scanf("%s",&str);
    int res = strncmp(str, "What is your name?", 100);
    if(res == 0)
      printf("I'm a program, I don't have a name!\n");
    res = strncmp(str, "How are you?", 100);
    if(res == 0)
      printf("Fine.\n");
    res = strncmp(str, "What do you think of wikiHow?", 100);
    if(res == 0)
      printf("It's great!");
  }
}

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...