473,804 Members | 2,101 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String Comparision

(Sorry if this gets posted twice)
Hi all. I am trying to learn C.As a simple exercise i tried to write a
code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get
modified somehow in the comp function and as a result i am getting
incorrect results.
Can anyone please point out the error?
#include<stdio. h>

int comp(char *s,char *t)
{
for(;*s==*t;s++ ,t++);
if(*s=='\0')
return 0;
else
return (*s -*t);
}

int main(void)
{
char str[]="Hello";
char str2[]="Hello";

if(comp(str,str 2)!=0)
printf("strings are different");
else
printf("strings are same");
return 0;
}
Apr 29 '07 #1
35 2906
"user34" writes:
Hi all. I am trying to learn C.As a simple exercise i tried to write a
code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get modified
somehow in the comp function and as a result i am getting incorrect
results.
Can anyone please point out the error?
#include<stdio. h>

int comp(char *s,char *t)
{
for(;*s==*t;s++ ,t++);
if(*s=='\0')
return 0;
else
return (*s -*t);
You return after examining the first char, no matter how it turns out.
Rethink your logic.
}

int main(void)
{
char str[]="Hello";
char str2[]="Hello";

if(comp(str,str 2)!=0)
printf("strings are different");
else
printf("strings are same");
return 0;
}

Apr 29 '07 #2
osmium wrote:
"user34" writes:
>Hi all. I am trying to learn C.As a simple exercise i tried to write a
code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get modified
somehow in the comp function and as a result i am getting incorrect
results.
Can anyone please point out the error?
#include<stdio .h>

int comp(char *s,char *t)
{
for(;*s==*t;s++ ,t++);
if(*s=='\0')
return 0;
else
return (*s -*t);

You return after examining the first char, no matter how it turns out.
Rethink your logic.
Can you elaborate? The for loop should parse the string until the
characters in the two strings differ ,is'nt it?
Apr 29 '07 #3
user34 wrote, On 29/04/07 17:53:
(Sorry if this gets posted twice)
Hi all. I am trying to learn C.As a simple exercise i tried to write a
code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get
modified somehow in the comp function and as a result i am getting
incorrect results.
Can anyone please point out the error?
First off, did you copy and paste or retype? I suspect you retyped and
in the process typed correctly what is wrong in the copy you ran.
#include<stdio. h>
They stopped charging for white space yesterday, so your could make the
above easier to read by doing
#include <stdio.h>
int comp(char *s,char *t)
Since this function is not meant to modify the strings it would be
better to make it explicit
int comp(const char *s,const char *t)

This will also mean the compiler will bitch at you if you try to modify
them.
{
for(;*s==*t;s++ ,t++);
It is easy to fail to spot the semicolon above, for the human reader
something like
for (; *s==*t; s++,t++) continue;
Or
for (; *s==*t; s++,t++) /* do nothing */ ;
Or
for (; *s==*t; s++,t++) {}

Also, what if both strings are entirely the same? In that case you will
not stop at the end of the strings but will continue going in to the
wild blue yonder.
for (; *s && *s==*t; s++,t++) continue;
if(*s=='\0')
return 0;
else
return (*s -*t);
You do not need the parenthesis
return *s - *t;

Also, on some embedded systems where a byte (in C terms) is 16 bits or
larger and the same size as an int this could fail.
return (*s *t) ? 1 : -1;
}

int main(void)
{
char str[]="Hello";
char str2[]="Hello";

if(comp(str,str 2)!=0)
printf("strings are different");
else
printf("strings are same");
return 0;
}
You should add a newline on to the end of the strings. One easy way as
you are not using any format specifiers is to call puts instead of printf.
--
Flash Gordon
Apr 29 '07 #4
user34 wrote, On 29/04/07 18:15:
osmium wrote:
>"user34" writes:
>>Hi all. I am trying to learn C.As a simple exercise i tried to write
a code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get
modified somehow in the comp function and as a result i am getting
incorrect results.
Can anyone please point out the error?
#include<stdi o.h>

int comp(char *s,char *t)
{
for(;*s==*t;s++ ,t++);
if(*s=='\0')
return 0;
else
return (*s -*t);

You return after examining the first char, no matter how it turns out.
Rethink your logic.

Can you elaborate? The for loop should parse the string until the
characters in the two strings differ ,is'nt it?
Also it won't stop at the end of the strings if they are the same.
--
Flash Gordon
Apr 29 '07 #5
jg
On Apr 29, 9:53 am, user34 <use...@invalid .comwrote:
for(;*s==*t;s++ ,t++);
Need to check both s and t are not pointing to somewhere
out of the string.
JG

Apr 29 '07 #6
Flash Gordon wrote:
user34 wrote, On 29/04/07 17:53:
>(Sorry if this gets posted twice)
Hi all. I am trying to learn C.As a simple exercise i tried to write a
code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get
modified somehow in the comp function and as a result i am getting
incorrect results.
Can anyone please point out the error?

First off, did you copy and paste or retype? I suspect you retyped and
in the process typed correctly what is wrong in the copy you ran.
I did not retype the code !
Here it is once again (without any of the above suggested
improvements)an d it still shows me the same error!

#include<stdio. h>

int comp(char *s,char *t)
{
for(;*s==*t;s++ ,t++);
if(*s=='\0')
return 0;
else
return (*s -*t);
}

int main(void)
{
char str[]="Hello";
char str2[]="Hello";

if(comp(str,str 2)!=0)
printf("strings are different");
else
printf("strings are same");
return 0;
}
Apr 29 '07 #7
user34 wrote, On 29/04/07 18:29:
Flash Gordon wrote:
>user34 wrote, On 29/04/07 17:53:
>>(Sorry if this gets posted twice)
Hi all. I am trying to learn C.As a simple exercise i tried to write
a code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get
modified somehow in the comp function and as a result i am getting
incorrect results.
Can anyone please point out the error?

First off, did you copy and paste or retype? I suspect you retyped and
in the process typed correctly what is wrong in the copy you ran.

I did not retype the code !
Here it is once again (without any of the above suggested
improvements)an d it still shows me the same error!
<snip>

Then your description of the problem is inaccurate, the code does not
modify the strings. I suggest you examine the improvements and comments
by myself and the others and see if it then works.
--
Flash Gordon
Apr 29 '07 #8
"user34" writes:
Hi all. I am trying to learn C.As a simple exercise i tried to write a
code which would compare two strings using pointers.
However i am not getting the correct result.
On tracing the program i noticed that the strings "s" and "t" get modified
somehow in the comp function and as a result i am getting incorrect
results.
Can anyone please point out the error?
#include<stdio. h>

int comp(char *s,char *t)
{
for(;*s==*t;s++ ,t++);
if(*s=='\0')
return 0;
else
return (*s -*t);
}

int main(void)
{
char str[]="Hello";
char str2[]="Hello";

if(comp(str,str 2)!=0)
printf("strings are different");
else
printf("strings are same");
return 0;
}
The first problem I note is that the terminating condition on the for loop
should be an '\0', signifying end of string. This suggests the middle
expression should be something like

*s!='\0' && *t'='\0'

But this doesn't work because we don't know if both strings are the same
length. So now we precede your code with something to find the length of
the strings. But that uses stuff in <string.h>, the very thing you are
trying to avoid! But then note that you are barely using a for loop, it is
a force fit. I suggest you rewrite using a while loop. I don't like
suggesting new and different ways to attack a problem, but even more, I
don't like the code I foresee if the for loop approach is continued.

I consider the primary good attribute of a for loop the index variable. But
you don't *use* an index variable.

Apr 29 '07 #9
"user34" wrote:
osmium wrote:
>You return after examining the first char, no matter how it turns out.
Rethink your logic.

Can you elaborate? The for loop should parse the string until the
characters in the two strings differ ,is'nt it?
If you really prefer a for loop based solution, I would do it something like
this. As far as I know it works.
--------------------------
#include <stdio.h>

// return 1 iff they are equal (inverted sense from what you had)
int comp(char a[], char b[])
{
for(int i=0; ; i++)
{
if(a[i] != b[i])
return 0;
/* assert: a[i] == b[i], we just tested it
but it it the end of the string? */
if(a[i] == '\0')
return 1;
}
}
/*=============*/
int main()
{
char s[] = "test";
char t[] = "test";
if(comp(s, t))
printf("Same\n" );
else
printf("Differe nt");
return 0;
}
Apr 29 '07 #10

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

Similar topics

7
10631
by: Forecast | last post by:
I run the following code in UNIX compiled by g++ 3.3.2 successfully. : // proj2.cc: returns a dynamic vector and prints out at main~~ : // : #include <iostream> : #include <vector> : : using namespace std; : : vector<string>* getTyphoon()
6
1855
by: rakesh | last post by:
Hi, I have a requirement in which I need to search a string in a file stored on a harddisk. String which needs to be searched would be stored in a file with delimiter as new line character. some of the ways of doing this are 1. Read each line and do string compare immediately. 2. Read each line, add each string into a stl vector and search for the given string using stl bineary_search algorithm.
32
49735
by: Wolfgang Draxinger | last post by:
I understand that it is perfectly possible to store UTF-8 strings in a std::string, however doing so can cause some implicaions. E.g. you can't count the amount of characters by length() | size(). Instead one has to iterate through the string, parse all UTF-8 multibytes and count each multibyte as one character. To address this problem the GTKmm bindings for the GTK+ toolkit have implemented a own string class Glib::ustring...
3
1644
by: kd | last post by:
Hi All, How to perform case-insensitive comparision of strings? Would there be some kind of an indicator, which when set to true, would allow case-insenitive comparision of strings using if/select case, etc; after performing the case-insenisitive compare, the indicator can be reset to allow the conventional comparision of strings? kd
2
2667
by: nirav.lulla | last post by:
I have been given the task to come up with Requirements, Comparision and Migration document from Shadow Direct to DB2 Connect. I am very new much to all this, but kind of know a little bit about both of them. There has been a lot of pressure from business to move to DB2 Connect from Shadow Direct which the company is currently using since almost 7 years. I would greatly appreciate if any one of you can help or send me some comparision...
30
3323
by: Steve Edwards | last post by:
Hi, I'm re-writing some code that had relied on some platform/third-party dependent utility functions, as I want to make it more portable. Is there a standard C/C++/stl routine for changing an stl string to all lowercase? (I know how to do it manually, but in the interests of portability...) Thanks Steve
33
4697
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most of articles I read from different experts and programmers tell me that their "gut feelings" for using stringBuilder instead of string concatenation is when the number of string concatunation is more then N ( N varies between 3 to max 15 from...
8
5745
by: abhi147 | last post by:
Hi all , I need to convert a 32 bit string containing hex digits like "76d408cedd600bb578bc0256a751cea2" into it's corresponding 16bit ascii value like "vÎÝ` µx¼V§Q΢" . Now the presence of Hex digits like "0a" ,"00" , "0b" whose ascii value is New line , NULL , Tab respectively brings the rest of the string to new line or put a tab in between .
9
5044
by: subramanian100in | last post by:
Suppose we have char *a = "test message" ; Consider the comparison if (a == "string") ..... Here "string" is an array of characters. So shouldn't the compiler
0
9714
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10351
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10096
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9174
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5534
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4311
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
2
3834
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.