none
C# program for String Compare without using String Functions

    Question

  • Hi,

     

    Does anyone knows C# program for String Compare without using String Functions?


    Regards

    Monday, January 14, 2008 10:57 AM

Answers

  • You mean something like this?
    Code Block

    /// <summary>
    /// Compares 2 strings
    /// </summary>
    /// <param name="str1">one of the 2 strings you want to compare</param>
    /// <param name="str2">one of the 2 strings you want to compare</param>
    /// <returns>true if the strings are equal</returns>
    public bool CompareStrings(string str1, string str2)
    {
        int length = str1.Length;
        if (length != str2.Length)
            return false;
        for (int i = 0; i < length; i++)
            if (str1[i] != str2[i])
                return false;
        return true;
    }


    Monday, January 14, 2008 11:41 AM
  • This is the source( .NET Reflector )
    Code Block
    namespace System
    {
    [Serializable, ComVisible(true)]
        public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
        {
            public static bool operator ==(string a, string b)
            {
                return Equals(a, b);
            }

            public static bool Equals(string a, string b)
            {
                return ((a == b) || (((a != null) && (b != null)) && EqualsHelper(a, b)));
            }

            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
            private static unsafe bool EqualsHelper(string strA, string strB)
            {
                int length = strA.Length;
                if (length != strB.Length)
                {
                    return false;
                }
                fixed (char* str = ((char*)strA))
                {
                    char* chPtr = str;
                    fixed (char* str2 = ((char*)strB))
                    {
                        char* chPtr2 = str2;
                        char* chPtr3 = chPtr;
                        char* chPtr4 = chPtr2;
                        while (length >= 10)
                        {
                            if ((((*(((int*)chPtr3)) != *(((int*)chPtr4))) || (*(((int*)(chPtr3 + 2))) != *(((int*)(chPtr4 + 2))))) || ((*(((int*)(chPtr3 + 4))) != *(((int*)(chPtr4 + 4)))) || (*(((int*)(chPtr3 + 6))) != *(((int*)(chPtr4 + 6)))))) || (*(((int*)(chPtr3 + 8))) != *(((int*)(chPtr4 + 8)))))
                            {
                                break;
                            }
                            chPtr3 += 10;
                            chPtr4 += 10;
                            length -= 10;
                        }
                        while (length > 0)
                        {
                            if (*(((int*)chPtr3)) != *(((int*)chPtr4)))
                            {
                                break;
                            }
                            chPtr3 += 2;
                            chPtr4 += 2;
                            length -= 2;
                        }
                        return (length <= 0);
                    }
                }
            }
        }


    Monday, January 14, 2008 7:44 PM

All replies

  • You mean something like this?
    Code Block

    /// <summary>
    /// Compares 2 strings
    /// </summary>
    /// <param name="str1">one of the 2 strings you want to compare</param>
    /// <param name="str2">one of the 2 strings you want to compare</param>
    /// <returns>true if the strings are equal</returns>
    public bool CompareStrings(string str1, string str2)
    {
        int length = str1.Length;
        if (length != str2.Length)
            return false;
        for (int i = 0; i < length; i++)
            if (str1[i] != str2[i])
                return false;
        return true;
    }


    Monday, January 14, 2008 11:41 AM
  •  Ansaar wrote:

    Hi,

     

    Does anyone knows C# program for String Compare without using String Functions?


    Regards

     

    The purpose of the assignment is for you to learn to think abstractly about a problem and how to go about solving it with the given tool (C# language in this case).

     

    Asking for someone to give you the answer isn't going to help you very much. You need to work through the exercise in your head by thinking about it logically.

     

    What does it mean to "compare two strings"? To compare two strings for equality you must discover if both strings contain the same values.

     

    1) The first very simple test is to see if they both have the same length. If they do not, they cannot possibly be the same strings.

    2) Now that we know they are the same length we can iterate through each character in both strings and test if they are the same character. If at any point we find different characters, then they cannot be the same string.

     

    You're not quite done yet. If you got this far it would seem that you have solved the problem. Let's test our thinking with some examples:

     

    "Hello, world!" vs. "Hello, world!"

     

    Sure enough, they are the same strings because they have the same length and every character in the first string matches every character in the second.

     

    But what about:

    "hello, world!" vs. "Hello, world!"

     

    Are they the same string? If we use our steps above to test them, the result will be that they are not the same string. Why? Because 'h' is not the same character as 'H'. Although they have the same meaning in the English language, they do not have the same numeric representation in a computer (they have to be different don't they? how else would the computer know how to display one or the other?).

     

    Given this knowledge, you have to make a decision: Do I want to know if the strings match exactly or do I want to know if they mean the same thing? If this string was entered by a person and represented a person's name, you would probably want to test for meaning, not for exact characters. When we compare two strings exactly, we say that is a "case-sensitive" comparison because the case of each letter is important. When we compare two strings by meaning we say that is a "case-insensitive" comparison. The decision to use one compare over the other is entirely dependent on the context of the information contained in the strings.

     

    So now you have two answers to your question: One for a case-sensitive comparison and one that's insensitive.

     

    You've been given one answer, can you solve the question for the second?

     

    Monday, January 14, 2008 6:44 PM
  • p.s. In C# all strings that are character-for-character identical have exactly the same reference value:

     

    string s1 = "hello";

    string s2 = "hello";

     

    The runtime only creates one instance of the string object "hello" and both s1 and s2 reference it (point to it). What this means is that for C#, you can perform a case-sensitive comparison on two strings by using the equality operator:

     

    if (s1 == s2) ...

     

    This also makes case-insensitive comparisons easy:

     

    if (s1.ToLower() == s2.ToLower()) ...

     

    Since whatever string(s) produced by the String.ToLower function will be reference identical if they are the same.

     

    This of course does not answer the above question since the assignment specifically said you could not use the String functions

    Monday, January 14, 2008 6:56 PM
  • thats not correct.
    your are calling string.operator== with
    if( s1 == s2 ) ...
    to check the reference you have to use
    if( object.ReferenceEquals(s1,s2) )
    Monday, January 14, 2008 7:15 PM
  • It is correct. String.operator== is implemented as object.ReferenceEquals. Check the IL if you don't believe me. Or better yet, let me find some documentation to back up my statements...

     

    Monday, January 14, 2008 7:37 PM
  • Here is a blurb on the intern pool:

    http://msdn2.microsoft.com/en-us/library/system.string.isinterned.aspx

     

    Let me see if I can find the operator== implementation note...

     

    Monday, January 14, 2008 7:42 PM
  • This is the source( .NET Reflector )
    Code Block
    namespace System
    {
    [Serializable, ComVisible(true)]
        public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
        {
            public static bool operator ==(string a, string b)
            {
                return Equals(a, b);
            }

            public static bool Equals(string a, string b)
            {
                return ((a == b) || (((a != null) && (b != null)) && EqualsHelper(a, b)));
            }

            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
            private static unsafe bool EqualsHelper(string strA, string strB)
            {
                int length = strA.Length;
                if (length != strB.Length)
                {
                    return false;
                }
                fixed (char* str = ((char*)strA))
                {
                    char* chPtr = str;
                    fixed (char* str2 = ((char*)strB))
                    {
                        char* chPtr2 = str2;
                        char* chPtr3 = chPtr;
                        char* chPtr4 = chPtr2;
                        while (length >= 10)
                        {
                            if ((((*(((int*)chPtr3)) != *(((int*)chPtr4))) || (*(((int*)(chPtr3 + 2))) != *(((int*)(chPtr4 + 2))))) || ((*(((int*)(chPtr3 + 4))) != *(((int*)(chPtr4 + 4)))) || (*(((int*)(chPtr3 + 6))) != *(((int*)(chPtr4 + 6)))))) || (*(((int*)(chPtr3 + 8))) != *(((int*)(chPtr4 + 8)))))
                            {
                                break;
                            }
                            chPtr3 += 10;
                            chPtr4 += 10;
                            length -= 10;
                        }
                        while (length > 0)
                        {
                            if (*(((int*)chPtr3)) != *(((int*)chPtr4)))
                            {
                                break;
                            }
                            chPtr3 += 2;
                            chPtr4 += 2;
                            length -= 2;
                        }
                        return (length <= 0);
                    }
                }
            }
        }


    Monday, January 14, 2008 7:44 PM
  • (edit: original reply did not make it clear that I was accepting that I was wrong. I was wrong.)

     

    return (a == b) OR ...

     

    So it would appear that if it fails the reference compare, it goes on to check the strings.. Maybe that's because in 2.0 or later you can bypass the intern pool (which I didn't know until just now).

    Monday, January 14, 2008 8:04 PM