有没有一种方法可以计算C中的令牌? [英] Is there a way to count tokens in C?

查看:115
本文介绍了有没有一种方法可以计算C中的令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 strtok 将字符串拆分为令牌。没有人知道实际上计算令牌数量的任何函数吗?

I'm using strtok to split a string into tokens. Does anyone know any function which actually counts the number of tokens?

我有一个命令字符串,我需要将其拆分并将参数传递给 execve()

I have a command string and I need to split it and pass the arguments to execve() .

谢谢!

编辑 >

execve 接受参数为 char ** ,所以我需要分配一个指针数组。我不知道要分配多少令牌而不知道有多少令牌。

execve takes arguments as char**, so I need to allocate an array of pointers. I don't know how many to allocate without knowing how many tokens are there.

推荐答案

一种方法是简单地使用 strtok 和一个计数器。但是,这将修改原始字符串。

One approach would be to simply use strtok with a counter. However, that will modify the original string.

另一种方法是在循环中使用 strchr ,如下所示:

Another approach is to use strchr in a loop, like so:

int count = 0;
char *ptr = s;
while((ptr = strchr(ptr, ' ')) != NULL) {
    count++;
    ptr++;
}

如果有多个定界符,请使用 strpbrk

If you have multiple delimiters, use strpbrk:

while((ptr = strpbrk(ptr, " \t")) != NULL) ...

这篇关于有没有一种方法可以计算C中的令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆