如何安全解析制表符分隔的字符串? [英] How to safety parse tab-delimited string ?

查看:105
本文介绍了如何安全解析制表符分隔的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何安全分析制表符分隔符字符串?例如: test \ tbla-bla-bla \ t2332吗?

How to safety parse tab-delimiter string ? for example: test\tbla-bla-bla\t2332 ?

推荐答案

strtok()是用于解析带有任意定界符的字符串的标准函数.但是,它不是线程安全的.您选择的C库可能具有线程安全的变体.

strtok() is a standard function for parsing strings with arbitrary delimiters. It is, however, not thread-safe. Your C library of choice might have a thread-safe variant.

另一种符合标准的方式(只写了一下,这是未经测试的):

Another standard-compliant way (just wrote this up, it is not tested):

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

int main()
{
    char string[] = "foo\tbar\tbaz";
    char * start = string;
    char * end;
    while ( ( end = strchr( start, '\t' ) ) != NULL )
    {
        // %s prints a number of characters, * takes number from stack
        // (your token is not zero-terminated!)
        printf( "%.*s\n", end - start, start );
        start = end + 1;
    }
    // start points to last token, zero-terminated
    printf( "%s", start );
    return 0;
}

这篇关于如何安全解析制表符分隔的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆