Thread: strncmp like function in C#

  1. #1
    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,820
    What is wrong with string.compare?
    http://msdn2.microsoft.com/en-us/library/84787k22.aspx

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    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
    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, 03:06 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  4. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  5. const at the end of a sub routine?
    By Kleid-0 in forum C++ Programming
    Replies: 14
    Last Post: 10-23-2005, 06:44 PM