|
-
Aug 19th, 2002, 05:46 AM
#1
Thread Starter
Fanatic Member
simple character comparison doesn't work
I'm trying to write a function which will return number of occurences of a character in a string. For exampale, "o" is found 2 times in "london".
int nchar(char* s, char* m)
{
int i=0;
while(*s != '\0')
{
printf("chars are %c,%c\n",*s,*m);
printf("ascii value %d,%d\n",atoi(s),atoi(m));
if(strcmp(s,m)==0)
{
printf("matched");
i++;
}
s++;
}
return i;
}
I also tried with atoi(*s)==atoi(*m) instead of strcmp but still doesn't work (compiles but can't find match)
I'm calling the function as follows
int j=0;
j=nchar("london","o");
printf("found times %d\n",j);
Please help.
thank you.
Life is a one way journey, not a destination. Travel it with a smile and never regret anything.
Yesterday is history, tomorrow is a mystery, today is gift - that's why we call it present.
-
Aug 19th, 2002, 06:17 AM
#2
Thread Starter
Fanatic Member
it seems instead of strcmp only *s==*m works!
can you explain why?
Life is a one way journey, not a destination. Travel it with a smile and never regret anything.
Yesterday is history, tomorrow is a mystery, today is gift - that's why we call it present.
-
Aug 20th, 2002, 08:49 AM
#3
Thread Starter
Fanatic Member
I found the answer!
with strcmp it is actually comparing with "ondon" with "o" then "ndon" with "o" and so on.
That's why *s == *m works!
Life is a one way journey, not a destination. Travel it with a smile and never regret anything.
Yesterday is history, tomorrow is a mystery, today is gift - that's why we call it present.
-
Aug 20th, 2002, 09:14 AM
#4
Frenzied Member
Simplified a little:
Code:
int nchar(char* s, char* m)
{
int i=0;
while(*s!=0x00) if(*s++ == *m) i++;
return i;
}
0x00 is the same as '\0' just a bad habit on my part.
-
Aug 20th, 2002, 03:08 PM
#5
transcendental analytic
maybe even this 
Code:
int nchar(char* s, char* m)
{
int i=0;
while(*s!=0x00) i+=*s++ == *m;
return i;
}
Use  
writing software in C++ is like driving rivets into steel beam with a toothpick.
writing haskell makes your life easier:
reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|