标记多个字符串C.

时间:2014-03-01 18:20:27

标签: c arrays string tokenize

例如,我有:

char *string = "S 27 64 Stack";
char *string2 = "R 9 3 Overflow";

我如何将它们分成不同的字符串?我希望他们像:

char *temp,*temp2,*temp3;
temp = S, temp2 = 27, temp3 = 64. Or:
temp = R, temp2 = 9, temp3 = 3.

我不知道用户是输入一位数字还是一位数字。我写道:

char *input; input = malloc(100*sizeof(char));
char *temp, *temp2,*temp3;

   else if(input[0] != NULL){


      if( *(input+2) != ' ' && *(input+4) != '0'){

       temp = strtok(input, " ");
       temp2 = strtok(input+2," ");
       temp3 = strtok(input+4," ");

      }

      else if( *(input+3) != ' '){

       temp = strtok(input, " ");
       temp2 = strtok(input+2, " ");
       temp3 = strtok(input+5, " ");
      }

   }

当我尝试单独使用一位数算法或两位数算法时,没有问题。但是,当我尝试链接它们并一起使用时,我只看到Segmentation Fault(Core dumped)错误。

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

第二次和第三次调用strtok应该有一个NULL作为第一个参数,尝试替换

temp = strtok(input, " ");
temp2 = strtok(input+2," ");
temp3 = strtok(input+4," ");

通过

temp = strtok(input, " ");
temp2 = strtok(NULL, " ");
temp3 = strtok(NULL, " ");

如果输入[2],...

,则不需要if输入[0]

请参阅strtok的文档:http://www.cplusplus.com/reference/cstring/strtok/