Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

file - How do I use strtok with every single nonalpha character as a delimeter? (C)

So I have a string:

**BOB**123(*&**blah**02938*(*&91820**FOO**

I want to be able to use strtok to deliminate each word. The delimiter is every single character that is not a letter.

I was suggested to us isalpha, but not sure how I would go about this. Is there a way to do this without naming every single non-alpha character?

Unfortunately NOT allowed to use regex libraries.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
#include <stdio.h>
#include <ctype.h>

char *strtok_t(char *str, int (*test)(int ch)){
    static char *store = NULL;
    char *token;
    if(str != NULL){
        store = str;
    }
    if(store == NULL) return NULL;
    while(*store && !test(*store)){//skip delimiter
        ++store;
    }
    if(*store == '') return NULL;
    token=store;
    while(*store && test(*store)){
        ++store;
    }

    if(*store == ''){
        store = NULL;
    } else {
        *store++ = '';
    }
    return token;
}

int main(void){
    char str[128] = "BOB123(&blah02938(*&91820FOO";
    char *token;
    for(token = strtok_t(str, isalpha); token ; token = strtok_t(NULL, isalpha)){
        printf("%s
", token);
    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...