首页 > 解决方案 > 在 C 中拆分 char 数组,同时保留分隔符

问题描述

所以我在 C 中工作并且有一个 char 数组,我想在每次有空格、“(”、“)”或“{”时拆分它。但是,我想保留那些字符分隔符。例如,如果我的输入是

void statement(int y){

我希望我的输出是

void statement ( int y ) {

解决这个问题的最佳方法是什么?

标签: cregexsplit

解决方案


您可以使用您选择的循环和一些条件测试来完成它,这些条件测试基本上可以归结为:

  1. 如果当前 char 是分隔符;
  2. 如果前一个字符不是分隔符,则在分隔符之前输出一个空格;
  3. 如果分隔符(当前字符)不是空格,则输出字符后跟换行符。

(使用分隔符字符串作为字符串strchr并检查当前字符是确定当前字符是否为分隔符的简单方法)

将其放在一个简短的示例中,您可以执行以下操作:

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

int main (void) {

    int c, last = 0;                    /* current & previous char */
    const char *delims = " (){}";       /* delimiters */

    while ((c = getchar()) != EOF) {    /* read each char */
        if (strchr (delims, c)) {       /* if delimiter */
            if (last && !strchr (delims, last)) /* if last not delimiter */
                putchar ('\n');         /* precede char with newline */
            if (c != ' ') {             /* if current not space */
                putchar (c);            /* output delimiter */
                putchar ('\n');         /* followed by newline */
            }
        }
        else    /* otherwise */
            putchar (c);                /* just output char */
        last = c;                       /* set last to current */
    }
}

示例使用/输出

给定您的输入字符串,输出与您提供的匹配。

$ printf "void statement(int y){" | ./bin/getchar_delims
void
statement
(
int
y
)
{

如果您还有其他问题,请仔细查看并告诉我。


推荐阅读