Praveen,
While algorithmically correct, the use of the Substring method in your
code qualifies it for the "Really Bad Code of the Day" award ! What
most people seem to forget is that a string is nothing but an array of
chars. Use that array to iterate... why in the world do you need to
call Substring repeatedly ?
Here's my version of your code: (Typed in here so watch for syntax/
typos)
---
private bool Compare(string a, string b)
{
if (a.Length == b.Length)
{
int len = a.Length;
for (int i = 0; i < len; i++)
{
if (a[i] != b[i])
return false;
}
return true;
}
return false;
}
---
As Charles suggested, the code should probably be modified to allow
for case insensitive comparison, but my sample provides for a
simplistic example, mainly to illustrate a point.
On a side note to the OP, one way to frustrate your teacher could be
to write the following code function :
---
private bool Compare(string a, string b)
{
if (a == b)
return true;
else
return false;
}
---
Tell your teacher that YOU haven't used String.Compare... even if the
framework will call it internally. :P
On Dec 12, 9:58 am, "Praveen Kumar" <[email protected]> wrote:
> Hi,
>
> You can write program for Comparing string in C# without using
> String.Compare() function.
>
> bool CompareString(string source, string dest)
>
> {
>
> if(source.Length != dest.Length)
>
> return false;
>
> int sourceLen = source.Length;
>
> for(int iCounter = 0; iCounter < sourceLen; iCounter++)
>
> {
>
> if(source.Substring( iCounter, 1) != dest.Substring( iCounter, 1))
>
> return false;
>
> }
>
> return true;
>
> }
>
> Hope this code will help you.
>
> Regards,
> Praveen
>
> On Fri, Dec 12, 2008 at 2:08 AM, [email protected]
> <[email protected]>wrote:
>
>
>
>
>
> > Currently i'm learning to use C# at school.
> > Last lesson I had learned about strings, and got some homework to get
> > done.
> > So here it is :
> > 1) Make a function that will get two strings, check if they are the
> > same, and then return false\true. (The teacher said "DO NOT USE
> > STRING.COMPARE"). I tried do this one using FOR, but I always get out
> > of the index bounds. (here is my function) :
> > static bool GetNCheck(string s, string p)
> > {
> > int o = s.Length-1;
> > int i = 0;
> > if (s[s.Length - 1] < p[p.Length - 1])
> > o = p.Length - 1;
> > for (; s[i] == p[i] && i < o; i++) ;
> > if (i == s.Length-1 && i == p.Length-1)
> > return true;
> > return false;
> > }
>
> > 2)MAke a function that get a string, check if it have any numbers in
> > it, and then return false\true.
>
> > thanks :D- Hide quoted text -
>
> - Show quoted text -