Home > other >  Skipping Characters in C
Skipping Characters in C

Time:10-08

    char string[10] = "1    2 3, \n4, 5\n 2; 3 is fun 1 2! 3";
    char *token = strtok(string, " ");
    for (int i =0; i < sizeof(string) / sizeof(char) ; i  ){
        if (isspace(string[i]) == 0 || string[i] != "." || string[i] != ";" || string[i] != "," || string[i] != "!") {
            printf("word %c\n", string[i]);
        }
    }

I am pretty sure what I am trying to do is a bit obvious, but how do I do it? What I am actually trying to do is to use strtok(string, "any white space or, !; etc..") Then I was searching for how to ignore these characters generally in a string.

my problem is that it takes \n4 as one character I believe even in the case of 3, it would take 3, as one character

    char *token = strtok(string, " ");
    while(token != NULL){
        words[count] = token;
        count  ;
        token = strtok(NULL, " ");
    }

This is the thing I am actually trying to implement, but here it only removes spaces.

CodePudding user response:

Please don't write this:

char *token = strtok(string, " ");
    while(token != NULL) {
        words[count] = token;
        count  ;
        token = strtok(NULL, " ");
    }

The function designer made it SO VERY EASY

for( char *tkn = string; ( tkn = strtok( tkn, " " ) ) != NULL; tkn = NULL )
    /* do stuff with tkn */

ONE invocation of the function, ONE instance of the separator string.


If you want a non-destructive version of strtok() you can write your own. Here's something to work from.

int main() {
    char *p = "1    2 3, \n4, 5\n 2; 3 is fun 1 2! 3";

    char *rjct = " ,\n;!";

    while( *p ) {
        while( *p &&  strchr( rjct, *p ) ) p  ;
        while( *p && !strchr( rjct, *p ) ) putchar( *p   );
        printf( "-SEP-" ); // or simply putchar( ' ' );
    }
    putchar( '\n' );

    return 0;
}
1-SEP-2-SEP-3-SEP-4-SEP-5-SEP-2-SEP-3-SEP-is-SEP-fun-SEP-1-SEP-2-SEP-3-SEP-
  • Related