我有:
char *str = "abc def abcdef ghi xyz";
Run Code Online (Sandbox Code Playgroud)
我想分配
const char *a = "abc";
const char *b = "def";
const char *c = "abcdef";
const char *d = "ghi";
const char *e = "xyz";
Run Code Online (Sandbox Code Playgroud)
这里的关键是空格数可以多于一个.
请建议一个有效的方法.
这是一些使用的示例代码strok_r.它是可重入的版本strtok(不确定它是否是C标准的一部分).另外,我假设你只有5个令牌.如果你想拥有更多,你将不得不修改代码以使用分配额外的内存realloc.
#include <string.h>
#include <stdio.h>
int main(void)
{
const char *str = "abc def abcdef ghi xyz";
char *dup = strdup( str );
char **output = malloc( 5 * sizeof(char *) );
char *p = dup;
char *nextp = NULL;
int i = 0;
if( dup == NULL ) {
// handle error
}
for( i = 0; i < 5; ++i ) {
output[i] = strtok_r( p, " ", &nextp );
p = NULL;
}
for( i = 0; i < 5; ++i ) {
printf( "output[%d] = %s\n", i, output[i] );
}
free( dup );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |