我想实现一个C函数,用于分隔成对括号中的内容。结果存储在二维char数组中,每行存储一个标记。 在C中没有正则表达式。所以我想知道可以使用哪些内置函数来实现它?
例如,如果输入为(* 5 10 (Expression1) 100 (Expression2))
,则结果将是内容为*
,5
,10
,(Expression1)
的char数组, 100
和(Expresssion2)
。
答案 0 :(得分:1)
好的,从评论开始,你的解析选项几乎总是一样的。您可以沿着字符串向下移动指针,手动将标记分成数组,也可以使用strtok
或strsep
函数。下面的示例使用strtok
将字符串分隔为array
(一个静态声明的指针数组),其中可用的标记最多为64
个指针(由#define MAXTOK 64
定义)开始)。
一个简单的指针p
和strlen
用于跳过开始和结束'()'
,方法是在第二个字符处开始解析并用{覆盖最后一个')'
{1}}字符:
null-terminating
<强>输出强>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTOK 64
int main (void) {
char s[] = "(* 5 10 (Expression1) 100 (Expression2))";
char *array[MAXTOK] = {NULL};
char *p = s;
size_t idx = 0;
size_t len = 0;
size_t i;
len = strlen (s);
p++; /* skip opening '(' */
s[len-1] = 0; /* skip closing ')' */
/* parse remaining string into tokens stored in array */
for (p = strtok (p, " "); p; p = strtok (NULL, " ")) {
array[idx++] = strdup (p); /* allocate mem for tok, assign to array */
if (idx == MAXTOK) { /* check max number of pointers filled */
fprintf (stderr, "warning: max tokens filled.\n");
break; /* if you dynamically declare array, you can realloc */
}
}
for (i = 0; i < idx; i++)
printf (" array[%2zu] = %s\n", i, array[i]);
/* free memory allocated by strdup */
for (i = 0; i < idx; i++)
free (array[i]);
return 0;
}
这是一种标准方法。您的另一个选择是动态声明$ ./bin/parse_expr
array[ 0] = *
array[ 1] = 5
array[ 2] = 10
array[ 3] = (Expression1)
array[ 4] = 100
array[ 5] = (Expression2)
,并根据需要在最初时分配char **array;
(或calloc
)和malloc
的指针。