strncmp like function in C#

This is a discussion on strncmp like function in C# within the C# Programming forums, part of the General Programming Boards category; Hi all! I try to code a strncmp like function in C# but it does not work. Thanks for any ...

  1. #1
    x77
    x77 is offline
    Registered User
    Join Date
    Jul 2007
    Posts
    8

    strncmp like function in C#

    Hi all!

    I try to code a strncmp like function in C# but it does not work.
    Thanks for any help or comments :-)!

    Code:
    public static int strncmp (string s1, string s2, int num)
    {
                int i;
                for (i = 0; i < num; i++)
                {
                    if (s1[i] == s2[i])
                        return 1;
                   
    
                 }
    
              return 0;
    
    }

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,812
    What is wrong with string.compare?
    http://msdn2.microsoft.com/en-us/library/84787k22.aspx

  3. #3
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,272
    Interesting function. It returns 1 (no match) if any character matches. If no characters match, it returns 0 (meaning a match).

    You need to review what the return codes from strncmp() mean. 1 doesn't mean "the same." Also, this loop can potentially overrun the string. What if somebody passes a value for num which is larger than either of the two string lengths? Etc.

  4. #4
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    If you're just interested in equality use the overloaded == or != operator:
    Code:
    public bool Check(string s1, string s2)
    {
      return s1 == s2;
    }
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  5. #5
    x77
    x77 is offline
    Registered User
    Join Date
    Jul 2007
    Posts
    8
    Thanks for all!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 04:06 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 02:01 AM
  3. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 07:54 PM
  4. Replies: 28
    Last Post: 07-17-2006, 12:35 AM
  5. const at the end of a sub routine?
    By Kleid-0 in forum C++ Programming
    Replies: 14
    Last Post: 10-23-2005, 07:44 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21