473,503 Members | 1,136 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C: compare character

hi,
I want to compare character, if the string contains character "-" then it
will print Hello on the screen
however, neither method (1) nor method (2) work in the code below:
so what the correct code should be? thanks!

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
char *str;

*str = "abc - xyz";
for (i=0; i<35; i++){

/* method (1) does not work ! */
if (strcmp(str[i], "-") == 0) printf("Hello1");

/* method (2) shows nth ! */
if (str[i] == "-") printf("Hello2");
}

system("PAUSE");
return 0;
}

Nov 14 '05 #1
8 62635
Sharon wrote:
hi,
I want to compare character, if the string contains character "-" then it
will print Hello on the screen
however, neither method (1) nor method (2) work in the code below:
so what the correct code should be? thanks!

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
char *str;

*str = "abc - xyz";
Well, here's the first problem: You just dereferenced an uninitialized
pointer. Try replacing those last two lines with this:

char const* str = "abc - xyz";
for (i=0; i<35; i++){


/* method (1) does not work ! */
if (strcmp(str[i], "-") == 0) printf("Hello1");


str[1] is a character. strcmp only knows how to compare "strings" of
characters.
/* method (2) shows nth ! */
if (str[i] == "-") printf("Hello2");
You're comparing a single character ( str[i] ) to a string ( "-" ). I
can certainly understand why you might think this would work; it would
be very intuitive. Unfortunately, it doesn't work that way.

Try method (3):

if( str[i] == '-' ) printf( "Hello3\n" );
}

system("PAUSE");
return 0;
}


Good luck!

-Jeff

Nov 14 '05 #2
"Sharon" <sh************@hotmail.com> wrote in message
news:bs**********@news.hgc.com.hk...
hi,
I want to compare character, if the string contains character "-" then it
will print Hello on the screen
however, neither method (1) nor method (2) work in the code below:
so what the correct code should be? thanks!
Doesn't even compile ( VC++ 6.0 sp5 )
#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
char *str;
str is pointer to a character, right?
*str = "abc - xyz";
So, what is *str now?
for (i=0; i<35; i++){
The 35 here, why?
/* method (1) does not work ! */
if (strcmp(str[i], "-") == 0) printf("Hello1");
Oh, we have an array now?
Exactly which address in memory are we looking at?
Probably a good thing we didn't assign to it!
( Danger Will Robinson! )
/* method (2) shows nth ! */
if (str[i] == "-") printf("Hello2");
Ditto.
}

system("PAUSE");
return 0;
}

--

Cheers
--
Hewson::Mike
"This letter is longer than usual because I lack the time to make it
shorter" - Blaise Pascal
Nov 14 '05 #3
Sharon wrote:
hi,
I want to compare character, if the string contains character "-" then it
will print Hello on the screen
however, neither method (1) nor method (2) work in the code below:
so what the correct code should be? thanks!

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
char *str;

*str = "abc - xyz";
for (i=0; i<35; i++){
By the way, why are you iterating 35 times? Your string is not that long.

/* method (1) does not work ! */
if (strcmp(str[i], "-") == 0) printf("Hello1");

/* method (2) shows nth ! */
if (str[i] == "-") printf("Hello2");
}

system("PAUSE");
return 0;
}


Nov 14 '05 #4
In article <bs**********@news.hgc.com.hk>, sh************@hotmail.com
says...
hi,
I want to compare character, if the string contains character "-" then it
will print Hello on the screen


Look up 'strchr' in your favorite reference.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Nov 14 '05 #5
With credits to Jeff Schwab, below should be a working program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i=0, j=0;
char *str = "abc - xy-zdsd sdsd -x-y-";

while(str[i])
if (str[i++] == '-') printf("Found %d minus\n", ++j);

system("PAUSE");
return 0;
}

"Jeff Schwab" <je******@comcast.net> wrote in message
news:R8********************@comcast.com...
Sharon wrote:
hi,
I want to compare character, if the string contains character "-" then it will print Hello on the screen
however, neither method (1) nor method (2) work in the code below:
so what the correct code should be? thanks!

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
char *str;

*str = "abc - xyz";
for (i=0; i<35; i++){


By the way, why are you iterating 35 times? Your string is not that long.

/* method (1) does not work ! */
if (strcmp(str[i], "-") == 0) printf("Hello1");

/* method (2) shows nth ! */
if (str[i] == "-") printf("Hello2");
}

system("PAUSE");
return 0;
}


Nov 14 '05 #6
Sharon wrote:
hi,
I want to compare character, if the string contains character "-" then it
will print Hello on the screen
however, neither method (1) nor method (2) work in the code below:
so what the correct code should be? thanks!
It'll be worth rooting through your compiler docs to find the options
that'll make it "more fussy". I've inserted the complaints from mine into
your source.
#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
char *str;

*str = "abc - xyz"; ^^^
(9)
for (i=0; i<35; i++){

/* method (1) does not work ! */
if (strcmp(str[i], "-") == 0) printf("Hello1"); ^^^
(13)
/* method (2) shows nth ! */
if (str[i] == "-") printf("Hello2"); ^^^
(16) }

system("PAUSE");
return 0;
}
Your errors will differ. You'll get used to what they mean over time...

c.c: In function `main':
c.c:9: warning: assignment makes integer from pointer without a cast
^^^
I'll come back to this.

c.c:13: warning: implicit declaration of function `strcmp'
^^^
Tells me I've forgotten the header. strcmp() lives in <string.h>

c.c:13: warning: passing arg 1 of `strcmp' makes pointer from integer
without a cast
^^^
Mixing pointers and integers is almost always "a bad thing". Provided we've
included the header for it, it often means the arguments are wrong.

c.c:16: warning: comparison between pointer and integer
^^^
Ditto.

This should compile. It's still not in the "works" category though...

#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* strcmp */

int main()
{
int i;
const char str[]="abc - xyz"; /* a non-modifable string */

for (i=0; i<35; i++){

/* takes two string (const char*) arguments */
if (strcmp(str,"-") == 0) printf("Hello1");

/* compare a char with a char (single quotes) */
if (str[i] == '-') printf("Hello2");
}

/* no PAUSE command here so I deleted it */

return 0;
}

The major problem above is the loop. It's fixed at 35 characters but 'str'
is a lot shorter than that. Add a (size_t) variable to hold the result of
strlen() then use that value in the loop. Hint...

/* code */
const size_t len = strlen(str);
for (i = 0; i < len; i++) {
/* rest of code */
}

You'll note that the strcmp() decision will never occur unless 'str' is
exactly "-". Obviously it's not an exact match you're after so strcmp()
can't help here. There are a few search-like functions - probably the best
one for this is strchr(). It searches a string for the first (leftmost)
occurrence of a character and returns a pointer to it (if found) or NULL if
there isn't one.

#include <stdio.h>
#include <string.h>

int main()
{const char str[] ="abc - xyz";
const char *found;

found = strchr(str,'-');
if (NULL != found)
printf("got it\n");
else
printf("nope\n")
;
return 0;
}

The problem with your 'str'...
char *str;
*str = "abc - xyz";


....was that [char *str] just declared a pointer. There was no actual string
associated with it. This would have worked because it makes the 'str'
pointer point at the string literal "abc - xyz"...

char *str;
str = "abc - xyz";

....except for the fact string literals cannot be modified. You can often get
away with the above for historic reasons (old K&R C compilers were crap)
but in actual fact it should be...

const char *str;
str = "abc - xyz";

....the difference being that now the compiler will realise if you attempt to
modify "abc - xyz" with (eg str[0]='A') whereas it wouldn't realise without
the 'const' - it would really try to change "abc - xyz" into "Abc - xyz".
The effects of doing so range from it actually succeeding (almost
impossible to debug) to an instant crash (easy to find).
--
Guy Harrison
Nov 14 '05 #7
Lance wrote:
With credits to Jeff Schwab, below should be a working program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i=0, j=0;
char *str = "abc - xy-zdsd sdsd -x-y-";

while(str[i])
if (str[i++] == '-') printf("Found %d minus\n", ++j);

system("PAUSE");
return 0;
}


As it's nearly Crimbo... ;-)

printf("%s\n",strchr("abc - xyz",'-')?"yey":"ney");
--
Guy Harrison
Nov 14 '05 #8
Sharon wrote:
hi,
I want to compare character, if the string contains character "-" then it
will print Hello on the screen
however, neither method (1) nor method (2) work in the code below:
so what the correct code should be? thanks!


#include <string.h>
#include <stdio.h>

void checkforhyphen(const char *s)
{
if (strchr(s,'-')) puts("Hello");
/* printf("Hello") is closer to your spec, actually */
}
--
Martin Ambuhl

Nov 14 '05 #9

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

Similar topics

8
3717
by: Earl Purple | last post by:
On VC++.NET it is implemented like this static int __cdecl compare ( const _Elem *_First1, const _Elem *_First2, size_t _Count ) { // compare [_First1, _First1 + _Count) with [_First2, ...)...
5
39264
by: sieg1974 | last post by:
Hi, how can I compare one character of a string to a char? I have tried this to compare the first character of directory to '/', but when I run this program I got a segmentation fault. void...
15
2257
by: Beeeeeves | last post by:
Is there a quick way to find the index of the first character different in two strings? For instance, if I had the strings "abcdefghijkl" and "abcdefxyz" I would want the return value to be...
4
28014
by: Sasidhar Parvatham | last post by:
Hi All, How do I compare two strings and get all the positions where there is a difference between them? Thanks, Sasidhar
10
14456
by: lchian | last post by:
Hi, For two stl strings s1 and s2, I got different results from strcmp(s1.c_str(), s2.c_str()) and s1.compare(s2) can someone explain what these functions do? It seems that strcmp gives...
9
11335
by: Martoon | last post by:
I want to instantiate an STL map with my own compare function, and I want to pass a parameter to the compare function that will be stored and used for all comparisons in that map instance. As an...
4
24866
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...
3
7093
by: gaurav soni | last post by:
Hi, guys i am not very much familiar with c/c++ programming . i am trying to compare four ,character arrays i.e how and who are equal to each other. kindly update me ASAP . Thanku
17
3449
by: spasmous | last post by:
I need a way to search through a block of memory for a char array "DA" using a pointer to a short. Ideally I would like to write something like: short *data = ... some data...; int j = 0;...
0
7203
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,...
0
7089
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...
0
7282
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,...
0
7339
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...
0
7463
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...
1
5017
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3157
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
738
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
389
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...

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.