繁体   English   中英

如何在C中将字符串拆分为字符串数组?

[英]How to split a string into an array of strings in C?

我已经有这个问题很长时间了,所以我想问一下如何将字符串拆分为“单词”数组?

我已经尝试过 strtok 和 strtok_r 但它似乎并没有按照我想要的方式工作:

    char str[] = "This is a sentence.";

    // Returns first token
    char* token = strtok(str, " ");
    char *tokens[500];
  
    // Keep printing tokens while one of the
    // delimiters present in str[].
    
    
    for (int i = 0; i < 3; i++) {
        while (token != NULL) {
            token = strtok(NULL, " ");
            strcpy(tokens[i], token);
        }
        printf("%s\n", tokens[i]);
    }
    
    return 0;

这不会打印出任何东西,有人可以帮忙吗?

如果您想将str拆分为令牌并将令牌存储在缓冲区tokens中,您可以这样做(请查看我添加的评论):

char str[] = "This is a sentence.";

// Initialize tokens to NULL
char* tokens[500] = {0};

// Split the string in tokens and count the tokens:
size_t tokenCount = 0;
static size_t const max_token_count = sizeof(tokens) / sizeof(tokens[0]);
for (char* token = strtok(str, " ");
     token != NULL                  &&   tokenCount != max_token_count;
//   ^ Loop until there are tokens  and  ^ buffer not overflown
     token = strtok(NULL, " ")) {

    tokens[tokenCount++] = token;
    //                   ^ No need to allocate memory here, if you
    //                     are going to use tokens before str goes
    //                     out of scope.

}

// You may handle the case when there are more tokens in str that
// couldn't fit into buffer tokens here

for (size_t i = 0; i != tokenCount; ++i)
    puts(tokens[i]);

输出

This
is
a
sentence.

请注意,在上面代码段的末尾, str将被修改:空格将替换为字符'\0'

char str[] = "This is a sentence.";
//                ^  ^ ^

所以,如果你

puts(str);

只会得到

This

如果我正确理解您的需求,这是一个可能的帮助。 我使用制表符并删除所有对 strtok 的调用。

从此代码中,您将只打印第一个单词,我让您找到打印所有单词的方法:)

int main(){
    char str[] = "This is a sentence.";

    // Returns first token
    char tokens[500];
  
    // Keep printing tokens while one of the
    // delimiters present in str[].
    
    
    for (int i = 0; i < sizeof(tokens); i++) {
        if (str[i] == ' '){
            break;
        }
        tokens[i] = str[i];
    }
    printf("%s\n", tokens);

    
    return 0;
}

编辑

完整解决方案:

int main(){
    char str[] = "This is a sentence.";
    char tokens[500];
    memset(tokens,'\0', sizeof(tokens));

        for(int i=0, j=0; i< sizeof(tokens); i++)
        {

            if (str[i] == ' ' || str[i] == '\n' || str[i] == 0) {
                printf("%s\n", tokens);
                //reinit buffer token
                memset(tokens,'\0', sizeof(tokens));
                j=0;            
            }else{
                tokens[j] = str[i];
                j++;
            }
            if (str[i] == 0) {
                break;              //end of string found, exit the loop
            }

        }
    return 0;
}

输出

This  
is  
a  
sentence.  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM