c - 使用strtok解析数据

标签 c parsing strtok

我有一行数据

211L    CRYST1   60.970   60.970   97.140   90.000   90.000  120.000  P 32 2 1         6

我想用 C 进行解析。具体来说,我想将 P 32 2 1 提取为单个字符串。

当我使用 strtok 时,它使用所有空格作为分隔符,返回各个字符串

P
32
2
1

问题的更简洁的措辞:

如果我有可变数量的字符串(在本例中为 4 个),如何将它们连接成单个字符串?

到目前为止我的代码:

while (fgets(line,sizeof line, PDBlist)!=NULL)
{
    p=0;
    pch=strtok(line,"\t");
    sprintf(space[p],"%s",pch);

    while(pch!=NULL){
        pch=strtok(NULL," ");
        p++;
        sprintf(space[p],"%s",pch);

    }

for(i=8;i<(p-1);i++){

        if(i==(p-2))printf("%s\n",space[i]);
        else printf("%s ",space[i]);

        }   }*

最佳答案

如果行的格式始终如发布的示例所示,则使用 strtok() 的替代方法是 sscanf() 。它为行内容提供一定程度的验证,无需额外编码(例如,验证 float 值):

const char* input = "211L    CRYST1   ....";
char first_token[32];
char second_token[32];
float float_1, float_2, float_3, float_4, float_5, float_6;
char last_token[32];

/* The '%31s' means read next sequence of non-whitespace characters
   but don't read anymore than 31. 31 is used to leave space
   for terminating NULL character.

   '%f' is for reading a float.

   '%31[^\n]' means read next sequence of characters up to newline
   but don't read anymore than 31. */
if (9 == sscanf(input, "%31s %31s %f %f %f %f %f %f %31[^\n]",
                first_token,
                second_token,
                &float_1,
                &float_2,
                &float_3,
                &float_4,
                &float_5,
                &float_6,
                last_token))
{
    /* Successfully read 9 tokens. */
}

查看在线演示:http://ideone.com/To4ZP .

关于c - 使用strtok解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11941825/

相关文章:

c - "make all"连续两次不 't return "使 : Nothing to be done for 'all' . "

检查它是一个字符还是一个整数

C strtok 没有标记空标记值

c - Strtok 问题 C(EOF 字符?)

c++ - strtok - 缓冲区溢出

c - 求一个平面上的 4 个点是否构成一个矩形?

c - Chromium OS 是用什么语言编写的?

java - 将字符串解析为模式为 :"dd/MM/yyyy"的日期

python - pycparser 解析错误

python - 使用 lxml 和 xpath 加速 xml 解析过程