开发者

Finding characters within a string in C

I'm wri开发者_运维技巧ting an algorithm in C with netbeans to find asterisks in a string.

int main() {
    int M=0, i, j;
    scanf("%i",&M);
    int pos[M];
    char c[M];
    scanf("%s", c);

    i=0;
    j=1;

    while(c[i] != '\0'){
        if(c[i]=='*'){
            pos[j] = i;
            j++;
        }
        i++;
    }

    printf("Asterisks in positions: \n\n");

    for(j=1; j<=i; j++){
        printf("%i", pos[j]);
    }
    return 0;
}

But it doesn't work, it prints a lot of numbers even if M is a small number.


The problem seems to be you never take into account the number of characters found. You print the whole vector, using i instead of j to iterate. It's j that holds the number of matches.

Also, try using strchr, from cstring :)

Get the first position, then search again from the next character until null is returned.


The information regarding how many asterisks you found is stored in the counter j. This variable gets reset in the for loop:

for(j=1; j<=i; j++)

Furthermore, this for loop goes all the way up to i, which is the length of the your input string. Try reworking your loop as follows:

for(i=1; i<j; i++){    
    printf("%i", pos[i]);    
} 


After your while loop completes, j holds the total number of positions recorded, so you should be printing from pos[1] to pos[j]. Your current loop prints from pos[1] to pos[i]. Just invert the variables in your final loop:

for(i=1; i<=j; i++){
    printf("%i", pos[i]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜