Results 1 to 4 of 4

Thread: How to Compare Two Strings in C

  1. #1
    Join Date
    Aug 2006
    Posts
    168

    How to Compare Two Strings in C

    Does nay one know how to Compare two Strings in C Programming? Say, my program is about to receive a string "DEF", and I want to test if the string really contains "DEF". What is the best way to test it?

  2. #2
    Join Date
    May 2008
    Posts
    2,297

    Re: How to Compare Two Strings in C

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
      char w1[20];
      char wd2[20];
    
      printf("\n first character:\n1: ");
      scanf("%s", wd1);                              
    
      printf(" second character:\n 2: ");
      scanf("%s", wd2);                                 
    
     
      if(strcmp(wd1,wd2) == 0)
        printf("identical words");
      else
        printf("%s comes before %s", (strcmp(wd1, wd2) > 0) ? wd2 : wd1, (strcmp(wd1, wd2) < 0) ? wd2 : wd1);
    }

  3. #3
    Join Date
    Apr 2008
    Posts
    2,005

    Re: How to Compare Two Strings in C

    With strncmp you only check the first someSaneCharLimit number of characters.strlen() returns the length of a string, excluding the null. If they are the same up to that point they will be equal i.e. strncmp("abcd", "abch", 3) would return a 0 whereas strncmp("abcd", "abch", 4) would return a number greater than 0.

  4. #4
    Join Date
    May 2008
    Posts
    2,012

    Re: How to Compare Two Strings in C

    Code:
    #include<stdio.h>
    main()
    {
       
          
      while(st1[i]!='/0' &&st2[i]!='/0')
           if(st1[i]!=st2[i])
              flag=1;
        if(flag==1)
       printf("equal");
    }

Similar Threads

  1. Difference between two strings
    By Aman 1 in forum Software Development
    Replies: 5
    Last Post: 03-12-2013, 11:59 AM
  2. Files and strings in C
    By An1990 in forum Software Development
    Replies: 2
    Last Post: 10-05-2012, 10:11 PM
  3. How to use Strings in Python
    By Edmund-Windows in forum Software Development
    Replies: 5
    Last Post: 31-12-2010, 06:25 AM
  4. Struct and Strings in C
    By Ash maker in forum Software Development
    Replies: 5
    Last Post: 05-04-2010, 12:31 PM
  5. Read and compare character strings
    By TechGate in forum Software Development
    Replies: 5
    Last Post: 27-01-2010, 01:30 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,558,629.56330 seconds with 17 queries