【问题标题】:Parsing formatted C strings that are divided into parts解析分为几部分的格式化 C 字符串
【发布时间】:2020-07-21 05:04:24
【问题描述】:

我想实现一个分解给定字符串的函数。但我不知道该怎么做。任何帮助表示赞赏。

/* Parses *str and creates a new StringBundle object containing the
 * separate fields of *str.
 *
 * Pre: str points to a GIS record string, properly terminated
 *
 * Returns: a pointer to a new proper StringBundle object
 */
 StringBundle* createStringBundle(const char* const str){

 }

例如这个用'|'分隔的字符串:

901051|Becker|Locale|NM|35|Eddy|015|322833N|1040812W|32.4759521|-104.1366141|||||959|3146|
Carlsbad East|11/01/1992|

我想把它分解成一个字符串集合,其中一些可能是空的。

0 901051
1 Becker
2 Locale
3 NM
4 35
5 Eddy
6 015
7 322833N
8 1040812W
9 32.4759521
10 -104.1366141
11
12
13
14
15 959
16 3146
17 Carlsbad East
18 11/01/1992
19

我正在使用结构字符串包

/** A StringBundle contains an array of nTokens pointers to properly-
 * terminated C strings (char arrays).
 *
 * A StringBundle is said to be proper if:
 * -Tokens == NULL and nTokens == 0
 * or
 * -nTokens > 0 and Tokens points to an array of nTokens char pointers,
 * -each char pointer points to a char array of minimum size to hold
 * its string, including the terminator (no wasted space)
 */
 struct _StringBundle {
     char** Tokens; // pointer to dynamically-allocated array of char*
     uint32_t nTokens; // dimension of array pointed to by Tokens
 };

字段Tokenschar**,因为它指向char* 变量数组中的第一个元素。

我可以使用以下任何 c 库函数:malloc()、calloc()、realloc()、free()、strncpy()、memcpy()、strlen()、sscanf()。

【问题讨论】:

标签: c arrays parsing pointers struct


【解决方案1】:

一个最小的状态机(如果你想将字符捕获到新的字符串中,你只需要通过追加到字符串操作来替换 fputc()s):


#include <stdio.h>

int main(void)
{
int ch, pos,lin;

for (pos=lin=0;;) {
        ch = getc(stdin);
        if (ch != EOF && pos==0) printf("\n%d:" , lin);
        if (ch == EOF) break;
        switch (ch) {
        default: putc(ch,stdout); break;
        case '|': lin++; pos = 0; continue;
        case '\n': putc(ch,stdout); continue;
                }
        pos++;
        }
return 0;
}

用法:


echo '901051|Becker|Locale|NM|35|Eddy|015|322833N|1040812W|32.4759521|-104.1366141|||||959|3146|Carlsbad East|11/01/1992|' \
| ./a.out

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多