如何将字符串拆分为标记并将标记存储在不同的变量C语言中

时间:2016-09-22 21:05:40

标签: c

嗨,我用C语言编写了这个代码:将字符串拆分为标记,但我想要的是令牌存储在不同的变量中,例如: a [] = + 5000 b [] = - 9000 c [] = 7HH4 d [] = 0因为在最后一个逗号之后我想要一个变量的空间

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

int main()
{
char str[] = "+5000,-9000,7jj4,";

// Returns first token 
char *token = strtok(str, ",");

// Keep printing tokens while one of the
// delimiters present in str[].
while (token != NULL)
{
    printf("%s\n", token);
    token = strtok(NULL, "-");
}

return 0;
}

4 个答案:

答案 0 :(得分:1)

只需跟踪您拨打strtok的次数,并每次将字符串复制到适当的位置。

char a[50], b[50], c[50];
int count = 0;

char *token = strtok(str, ",");

// Keep printing tokens while one of the
// delimiters present in str[].
while (token != NULL)
{
    printf("%s\n", token);
    count++;
    switch (count) {
    case 1:
        strcpy(a, token);
        break;
    case 2:
        strcpy(b, token);
        break;
    case 3:
        strcpy(c, token);
        break;
    }
    token = strtok(NULL, "-");
}    

答案 1 :(得分:0)

您可以从strtok分配每个变量。

char *a, *b, *c;

a = strtok(str, ",");
b = strtok(NULL, ",");
c = strtok(NULL, ",");

答案 2 :(得分:0)

使用滚轮的乐趣是什么,C就是创造新的东西。这是代码 -

int main (void ){

char str[] = "+5000, -9000, 7jj4";
char *p_str = str;
char a[10], b[10], c[10];
size_t a_count = 0,b_count = 0,c_count = 0;     // Need new index ever time for new token strings
size_t index = 0;

     while( *p_str ){
       if(*p_str == ',' ) { 
         p_str++; index++; p_str++;     // you can ignore p_str++ here.
      }    
        if(index == 0 && *p_str != ',' ){
          a[a_count++] = *p_str;        
       } else if( index == 1 && *p_str != ',' ){ 
           b[b_count++] = *p_str; 
        } else if ( index == 2 && *p_str != '\0' ){
            c[c_count++] = *p_str; 
         }      
       p_str++;
    }
   a[a_count] = b[b_count] = c[c_count] = '\0';
   printf("A : " ); puts(a); 
   printf("B : " ); puts(b);
   printf("C : " ); puts(c);
 return 0;
}

注意:您也可以进行动态分配。

答案 3 :(得分:-1)

您需要为返回的每个令牌分配一个缓冲区并存储它。

.babelrc

希望应该有所帮助。