繁体   English   中英

在C中分割char数组,同时保留定界符

[英]Split char array in C while keeping delimiters

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

void statement(int y){

我希望我的输出是

void statement ( int y ) {

最好的方法是什么?

您可以通过选择的循环和一些条件测试来做到这一点,这些条件测试基本上可以归结为:

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

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

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

#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
)
{

仔细检查一下,如果您还有其他问题,请告诉我。

您可以尝试使用strpbrk ,它不仅可以通过简单地返回指向找到的定界符的指针来保留定界字符,而且还支持多个定界符。

例如,这应该做您想要的:

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

int main(int argc, char *argv[]) {
    char *input = "void statement(int y){a";
    char *delims = " (){";
    char *remaining = input;
    char *token;

     // while we find delimiting characters
    while ((token = strpbrk(remaining, delims)) != NULL) {
         // print the characters between the last found delimiter (or string beginning) and current delimiter
        if (token - remaining > 0) {
            printf("%.*s\n", token - remaining, remaining);
        }

         // Also print the delimiting character itself
        printf("%c\n", *token);

         // Offset remaining search string to character after the found delimiter
        remaining = token + 1;
    }

     // Print any characters after the last delimiter
    printf("%s\n", remaining);

    return 0;
}

输出中包含空格,因为您已包含 作为分隔符。 如果不希望这样,请在这样的条件下包装定界字符:

    if (*token != ' ') {
        printf("%c\n", *token);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM