c - 在 C 中拆分 char 数组,同时保留分隔符
问题描述
所以我在 C 中工作并且有一个 char 数组,我想在每次有空格、“(”、“)”或“{”时拆分它。但是,我想保留那些字符分隔符。例如,如果我的输入是
void statement(int y){
我希望我的输出是
void
statement
(
int
y
)
{
解决这个问题的最佳方法是什么?
解决方案
您可以使用您选择的循环和一些条件测试来完成它,这些条件测试基本上可以归结为:
- 如果当前 char 是分隔符;
- 如果前一个字符不是分隔符,则在分隔符之前输出一个空格;
- 如果分隔符(当前字符)不是空格,则输出字符后跟换行符。
(使用分隔符字符串作为字符串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
)
{
如果您还有其他问题,请仔细查看并告诉我。
推荐阅读
- python - 我目前正在创建一个字谜测试器。问题是当我添加两个完全相同的单词时,它应该打印 false 但 dosent
- r - 使用其他变量(如内置函数中的参数)在数据表中添加新变量
- php - 单元测试 guzzle http 承诺回调
- java - 当我启动应用程序时,使用 @around 的 Spring AOP 会抛出 org.springframework.beans.factory.BeanCreationException
- php - PHP反序列化变量
- angular - 材料日期选择器的 Unix 纪元双向数据绑定
- excel - 基于大于 0 的各种标准运行的 if 语句
- header - 以表单组输入值为条件的 Twig
- r - ' ' 的登录失败。将 DSN 与 Rstudio 连接到 MS SQL 2016 时
- google-cloud-dataflow - 不适用于使用 Apache Beam 的 ParDo 和 DoFn