简体   繁体   English

如果分隔符定义为字符,如何在 C 中使用 strtok

[英]How to use strtok in C if delimiter is defined as character

I'm trying to use strtok for a school assignment of mine, but the delimiter declared as a constant in the code is declared as a character, and I'm not allowed to change this.我正在尝试将 strtok 用于我的学校作业,但是在代码中声明为常量的分隔符被声明为字符,并且我不允许更改它。 This delimiter is supposed to be arbitrary and has to work for any value.这个分隔符应该是任意的,并且必须适用于任何值。 When I try to use strtok however, it expects a string.但是,当我尝试使用 strtok 时,它需要一个字符串。 What is a workaround for splitting up strings when the delimiter is strictly defined as a single char in C?当分隔符被严格定义为 C 中的单个字符时,拆分字符串的解决方法是什么?

You can use compound literal for that.您可以为此使用复合文字。

Examples:例子:

token = strtok(str, (char[]){'a',0});

or或者

const char delim = 'a';

token = strtok(str, (char[]){delim,0});

or if you need to use more chars you can define a macro或者如果您需要使用更多字符,您可以定义一个宏

#define MKS(...) ((char[]){__VA_ARGS__, 0})

/* ... */

    token = strtok(str, MKS('a', 'b', 'c', ','));

If you have a character constant like for example如果您有一个字符常量,例如

const char c = ' ';

then to use strtok you can declare a character array like然后使用 strtok 你可以声明一个字符数组,如

char delim[] = { c, '\0' };

or that is the same或者是一样的

char delim[2] = { c };

In fact you can write your own function strtok using the character and the function strchr .实际上,您可以使用字符和 function strchr编写自己的 function strtok

Here is a demonstration program.这是一个演示程序。

#include <stdio.h>
#include <string.h>

int main( void )
{
    char c = ' ';
    char s[] = "Hello World";

    char *start = s, *end = NULL;
    do
    {
        end = strchr( start, c );
        if ( end != NULL )
        {
            if ( end != start )
            {
                *end = '\0';
                puts( start );
            }

            start = end + 1;
        }
        else if ( *start )
        {
            puts( start );
        }
    } while ( end != NULL );
}

The program output is程序 output 是

Hello
World

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

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