Béla Karalyos Béla Karalyos - 6 days ago 5
C Question

Compare a string array component with a character

I have this function:

int foo(char *string, int x, int y)

Example input is:
-.-..-...-.
The program tokenises the string with the delimiter
-
. Then it counts the
.
in the tokens. The problem is the
db
variable does not change. After the counting the
db
has to be higher than
x
and lower than
y
. So -.-..-...- 2 3, the solution has to be 2.

char *token;
int length;
int i;
int db=0;
int igaz=0;
int j=1;

token = strtok(string, "-");
length = strlen(token);

while(token != NULL)
{
length = strlen(token);

for(i=0; i<length; i++);
{
if(token[i] == '.')
//if(strcmp(token[i],'.')==0)
{
db++;
}
}

if(db >= x && db <= y)
{
igaz++;
}
db=0;

token = strtok(NULL, "-");
j++;

}
return igaz;

Answer

There are multiple problems in your code. 1. For loop with semi colon.

for(i=0; i<length; i++);

This will just loop. But will not execute the for loop body.

  1. strlen() will return string length excluding '\0' at the end. So your for loop should be from 0 to length as below.

for(i=0; i<=length; i++);

  1. For loop is unnecessary as string has only '-' and '.'

This will do that.

int foo(char *string, int x, int y)
{
    char *token;
    int igaz =0;
    int db   = 0;

    token = strtok(string, "-");

    while(token != NULL)
    {
       db = strlen(token);


       if(db >= x && db <= y)
       {
           igaz++;
       }

       token = strtok(NULL, "-");

    }
    return igaz;

}
Comments