有一些令牌
的代码char word[30] = "This - is - my - cat";
const char s[2] = "- ";
char *token;
token = strtok(word, s);
while( token != NULL )
{
printf( " %s\n", token );
token = strtok(NULL, s);}
那么如何从令牌中获取字符串?例如,我想抓住"我的"。
答案 0 :(得分:0)
不确定你需要什么 - 这似乎是它 -
char *result[8]; // 8 is completely arbitrary here
char *token= strtok(word, s);
int i=0;
char keep[12]={0x0};
while( token != NULL )
{
printf( " %s\n", token );
result[i++]=token;
result[i]=NULL;
token = strtok(NULL, s);
}
// get one of the fields you want "my" == result[2]
strcpy(keep, result[2]);
result []必须有足够的元素来处理代码将在其上抛出的任意数量的子字符串。
答案 1 :(得分:0)
你的意思是这样的:
#include <string.h>
#include <stdio.h>
#define MAX_LENGTH_OF_A_TOKEN (10)
char word[30] = "This - is - my - cat";
const char s[3] = "- ";
const char str_my[3] = "my";
char buffer[MAX_LENGTH_OF_A_TOKEN];
int main()
{
char *token;
token = strtok(word, s);
while( token != NULL )
{
strncpy(buffer, token, strlen(token)+1);
{
/* Now you have a local copy of your token in buffer. Do whatever you please with it.*/
printf("%s\n", buffer);
}
token = strtok(NULL, s);
}
return 0;
}