Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Compare int with character 1

Status
Not open for further replies.

amarg

Programmer
Nov 19, 2002
106
0
0
IN
Hi,

I have one strings contains "12321234321"
and another variable int x = 2
I want to count how many times this 2 come in the string.

How i can do this.

--Amar
 
Try this.
int strcnt(char *str, int x) {
int y = 0;
while (*str++) {
if (*str == x) {
y++
}
return y
}


 
Hi,

It's always giving 0

Here is the code i tried

int strcnt(char *str, int x) {
int y = 0;
while (*str++) {
if (*str == x) {
y++;
}
}
return y;
}


void main()
{
char abc[] = "12343212343212";
int n = 2;

printf("%d\n", strcnt(abc, n));
}


Amar
 
My fault, I was still asleep.
Change the function:
int strcnt(char *str, char x)
Then declare your 'n' as type char.
That should work.

You could also look at using a conversion
function: atol(), atoi(), strtol(), etc,
for your char *str.

 
int strcnt(char *str, int x) {
int y = 0;
while (*str++) {
if (*str == (x+48)) {
y++;
}
}
return y;
}

void main()
{
char abc[] = "12343212343212";
int n = 2;
printf("%d\n", strcnt(abc, n));
}
Here *str gives the ASCII value. So the int passed has to be converted to an ASCII value. As the ASCII value of '0' is 48, so 48 is added to x and compared with *str
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top