I'm using strtok
to split a string into tokens. Does anyone know any function which actually counts the number of tokens?
我正在使用strtok将字符串拆分为令牌。有谁知道这实际上计数的令牌数量的任何功能?
I have a command string and I need to split it and pass the arguments to execve()
.
我有一个命令字符串,我需要拆分它并将参数传递给execve()。
Thanks!
Edit
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.
execve将参数作为char **,所以我需要分配一个指针数组。我不知道有多少分配而不知道有多少令牌。
2 个解决方案
#1
8
One approach would be to simply use strtok
with a counter. However, that will modify the original string.
一种方法是简单地将strtok与计数器一起使用。但是,这将修改原始字符串。
Another approach is to use strchr
in a loop, like so:
另一种方法是在循环中使用strchr,如下所示:
int count = 0;
char *ptr = s;
while((ptr = strchr(ptr, ' ')) != NULL) {
count++;
ptr++;
}
If you have multiple delimiters, use strpbrk
:
如果您有多个分隔符,请使用strpbrk:
while((ptr = strpbrk(ptr, " \t")) != NULL) ...
#2
4
As number of tokens is nothing but one more than the frequency of occurrence of the delimiter used. So your question boils down to find no. of times of occurrence of a character in a string
因为令牌的数量只不过是所使用的定界符的出现频率。所以你的问题归结为找不到。字符串中出现字符的次数
say the delimiter used in strtok function in c is ' '
说c中strtok函数中使用的分隔符是''
int count =0,i;
char str[20] = "some string here";
for(i=0;i<strlen(str);i++){
if(str[i] == ' ')
count++;
}
No. of tokens would be same as count+1
代币数量与count + 1相同
#1
8
One approach would be to simply use strtok
with a counter. However, that will modify the original string.
一种方法是简单地将strtok与计数器一起使用。但是,这将修改原始字符串。
Another approach is to use strchr
in a loop, like so:
另一种方法是在循环中使用strchr,如下所示:
int count = 0;
char *ptr = s;
while((ptr = strchr(ptr, ' ')) != NULL) {
count++;
ptr++;
}
If you have multiple delimiters, use strpbrk
:
如果您有多个分隔符,请使用strpbrk:
while((ptr = strpbrk(ptr, " \t")) != NULL) ...
#2
4
As number of tokens is nothing but one more than the frequency of occurrence of the delimiter used. So your question boils down to find no. of times of occurrence of a character in a string
因为令牌的数量只不过是所使用的定界符的出现频率。所以你的问题归结为找不到。字符串中出现字符的次数
say the delimiter used in strtok function in c is ' '
说c中strtok函数中使用的分隔符是''
int count =0,i;
char str[20] = "some string here";
for(i=0;i<strlen(str);i++){
if(str[i] == ' ')
count++;
}
No. of tokens would be same as count+1
代币数量与count + 1相同