473,583 Members | 3,037 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

string comparison

Hello i am newbie trying to learn C..I need to know about string
comparisons in C, without using a library function,...rec ently I was
asked this in an interview..I can write a small program but I was told
that wouldn't it be wise to first get the length of the strings..if it
doesn't match then they are not the same..I agreed...then he said..but
again that would be an overhead first measuring the length...and then
doing a character by character comparison...I was confused and was
wondering if anybody has an answer to this theory. I am only trying to
undestand...

thanks

Nov 14 '05 #1
46 5124
ya******@yahoo. com wrote:
# Hello i am newbie trying to learn C..I need to know about string
# comparisons in C, without using a library function,...rec ently I was
# asked this in an interview..I can write a small program but I was told
# that wouldn't it be wise to first get the length of the strings..if it

The interviewer is either a jackass (not uncommon) or trying to trick
you (also not uncommon). In general the only way to measure strings
in C is to scan them from the first character to the null character.
If you measure the strings first you're going to end up doing the same
scan twice.

In ANSI C, a string comparison function can look something like
int compare(char *a,char *b) {
int cc = 0; while (cc==0 && *a && *b) cc = *a++ - *b++;
if (cc!=0) ;
else if (*a) cc = 1;
else if (*b) cc = -1;
return cc;
}
Sometimes you can compare words in machine dependent fashion and get
a four or eight time speed up.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
You hate people.
But I love gatherings. Isn't it ironic.
Nov 14 '05 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

ya******@yahoo. com wrote:
Hello i am newbie trying to learn C..I need to know about string
comparisons in C, without using a library function,...rec ently I was
asked this in an interview..I can write a small program but I was told
that wouldn't it be wise to first get the length of the strings..if it
doesn't match then they are not the same..I agreed...then he said..but
again that would be an overhead first measuring the length...and then
doing a character by character comparison...I was confused and was
wondering if anybody has an answer to this theory. I am only trying to
undestand...


Consider this: in C, a string is just an array of char, with zero or more
significant characters, and a '\0' character which terminates the string.

The length of the string is the count of the significant characters, up to
(but not including) the '\0' character.

It is true that, if the length of one string is different from the length of
another string, then the strings are different.

However, all that is really saying is that, in a character-by-character
comparison, where one string has a '\0', the other does not.

So, yes, it would be ideal to determine the lengths of the strings, but you
can only do so through a character-by-character inspection of each string.
If you are already going to examine the strings character-by-character,
comparing each character position to '\0' (to find the end, and thus the
length, of each string), there is no reason why you should not compare each
character of one string to the correspondingly placed character of the other.

Indeed, identical strings will compare identically up to and including the
'\0' character of each string. Different strings will compare identical up to
the first character difference, which may include the '\0' of one string
comparing unequal to the corresponding character of another string.
A visual example might help

String 1 A B C \0
: : : : Identical
String 2 A B C \0

or

String 1 A B C \0
: : : x Different
String 2 A B C D \0

or

String 1 A B Q \0
: : x Different
String 2 A B C \0

or even

String 1 A B Q \0
x Different
String 2 Z Y X \0

- --
Lew Pitcher

Master Codewright & JOAT-in-training | GPG public key available on request
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFCuM2nagV FX4UWr64RApU+AJ 4lI1+ui+FjPPN29 OMYukiDF/QVsQCeIv9k
EhRxPiJaixr9YT9 PivVRUkw=
=EpUj
-----END PGP SIGNATURE-----
Nov 14 '05 #3
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

SM Ryan wrote:
[snip]
In ANSI C, a string comparison function can look something like
int compare(char *a,char *b) {
int cc = 0; while (cc==0 && *a && *b) cc = *a++ - *b++;
if (cc!=0) ;
else if (*a) cc = 1;
else if (*b) cc = -1;
return cc;
}


Or even

int compare_strings (char *a, char *b)
{
while (*a++ == *b++) ;
return (int)(*a-*b);
}

- --
Lew Pitcher

Master Codewright & JOAT-in-training | GPG public key available on request
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFCuNMSagV FX4UWr64RAmRkAK DbXBeL3v3qA5Q0z Wfjee9pgU4LGgCg 4u5y
yykp27lAPLGzgEt oXL7eTYw=
=FAF0
-----END PGP SIGNATURE-----
Nov 14 '05 #4
I suggest you may use *long* instead of *char* to get full capability
of register.
and keep one eye on snaping 32bit and 8bit.

Nov 14 '05 #5
Lew Pitcher wrote:
SM Ryan wrote:
[snip]
In ANSI C, a string comparison function can look something like
int compare(char *a,char *b) {
int cc = 0; while (cc==0 && *a && *b) cc = *a++ - *b++;
if (cc!=0) ;
else if (*a) cc = 1;
else if (*b) cc = -1;
return cc;
}


Or even

int compare_strings (char *a, char *b)
{
while (*a++ == *b++) ;
return (int)(*a-*b);
}


I'd mark both of these as wrong. Neither replicates strcmp(). ;)

--
Peter

Nov 14 '05 #6
Lew Pitcher wrote:
.... snip ...
Or even

int compare_strings (char *a, char *b)
{
while (*a++ == *b++) ;
return (int)(*a-*b);
}


There is a winged insect crawling over that :-)

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html

Nov 14 '05 #7
CBFalconer wrote:
Lew Pitcher wrote:

... snip ...

Or even

int compare_strings (char *a, char *b)
{
while (*a++ == *b++) ;
return (int)(*a-*b);
}


There is a winged insect crawling over that :-)


I don't think that bug has wings... ;-)

--
Morris Dovey
DeSoto Solar
DeSoto, Iowa USA
http://www.iedu.com/DeSoto
Nov 14 '05 #8
On Tue, 21 Jun 2005 19:03:16 -0700, yadurajj wrote:
Hello i am newbie trying to learn C..I need to know about string
comparisons in C, without using a library function,...rec ently I was
asked this in an interview..I can write a small program but I was told
that wouldn't it be wise to first get the length of the strings..if it
doesn't match then they are not the same.
That's a possible strategy if you are only testing for equality. But if
you also need to determine which of 2 unequal strings is greater then it
doesn't help.
.I agreed...then he said..but
again that would be an overhead first measuring the length...and then
doing a character by character comparison...I was confused and was
wondering if anybody has an answer to this theory. I am only trying to
undestand...


You have to consider whether the strings are likely to differ near the
start. If you have a 100 character string and they differed in the 2nd
character then determining the length would be a very costly operation
compared to just comparing the character sequences. And strings usually
do differ in the first couple of characters unless there is a strong
relationship between them already.

Lawrence
Nov 14 '05 #9
On Tue, 21 Jun 2005 22:54:11 -0700, Peter Nilsson wrote:
Lew Pitcher wrote:
SM Ryan wrote:
[snip]
> In ANSI C, a string comparison function can look something like
> int compare(char *a,char *b) {
> int cc = 0; while (cc==0 && *a && *b) cc = *a++ - *b++; if (cc!=0) ;
> else if (*a) cc = 1;
> else if (*b) cc = -1;
> return cc;
> }
> }

Or even

int compare_strings (char *a, char *b) {
while (*a++ == *b++) ;
return (int)(*a-*b);
}
}

I'd mark both of these as wrong. Neither replicates strcmp(). ;)


The bug in the second is easy to spot, and from what I can tell the first
compare() differs from strcmp() in that strcmp() treats its arguments as
unsigned char *, whereas compare() treats them as they are when passed in:
char *.

Is that what you were referring to? If so, the problem seems to be solved
by changing the first line and adding two:
int compare(char *a,char *b) {
becomes
int compare(char *_a,char *_b) {
unsigned char *a = (unsigned char *)_a;
unsigned char *b = (unsigned char *)_b;

I'm just going by my gcc implementation - I don't know whether the
standard requires strcmp to behave this way...

Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
23374
by: David Graham | last post by:
Hi I have been busy going through the last weeks postings in an attempt to absorb javascript syntax (I guess it's not possible to just absorb this stuff in a passive way - I'm getting way out of my depth with most of the posts, I will buy a good book and take some online tutorials) Anyway, I think I almost understand one of Mr Nielsen's...
2
2538
by: Neil Zanella | last post by:
Hello, Consider the following program. There are two C style string stack variables and one C style string heap variable. The compiler may or may not optimize the space taken up by the two stack variables by placing them at the same address (my g++ compiler does this). Therefore the output of the given C program is compiler dependent. What...
8
2786
by: Grant Wagner | last post by:
I'm a bit confused by String() (typeof 'string') vs new String() (typeof 'object'). When you need to access a method or property of a -String-, what type is JavaScript expecting (or rather, what should you provide), a -String object- or a -string-? Given the following benchmark: var t = (new Date()).getTime(); for (var ii = 0; ii <...
51
8250
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct code? many thx!
5
657
by: MaSTeR | last post by:
Can anyone provide a practical short example of why in C# I shouldn't compare two strings with == ? If I write this in JAVA String string1 = "Widget"; if (string1 == "Widget") System.Console.WriteLine("String1 Equal.");
4
7176
by: Peter Kirk | last post by:
Hi I am looking at some code which in many places performs string comparison using == instead of Equals. Am I right in assuming that this will in fact work "as expected" when it is strings involved? By "as expected" I mean that as long as the strings are instantiated using string literals, then == and Equals are the same. string s1 =...
4
24870
by: Jim Langston | last post by:
Is there any builtin lowercase std::string compare? Right now I'm doing this: if ( _stricmp( AmmoTypeText.c_str(), "GunBullet" ) == 0 ) AmmoType = Item_Ammo_GunBullet; Is there anything the standard library to do this? I'm not interested in Boost until it becomes part of the standard.
26
3793
by: Neville Lang | last post by:
Hi all, I am having a memory blank at the moment. I have been writing in C# for a number of years and now need to do something in VB.NET, so forgive me such a primitive question. In C#, I test whether a string has a value or not by the following syntax: if (thisString.Trim() == "") {
6
4333
by: aznimah | last post by:
hi, i'm work on image comparison. i'm using the similarity measurement which i need to: 1) convert the image into the binary form since the algorithm that i've use works with binary data for the computation 2) compare the string binary data to get the similarity or dissimilarity result. The problem is, i already done with the image (jpg)...
0
7890
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8168
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8316
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7926
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8187
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5367
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3812
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2322
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1149
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.