我正在尝试使用 c 代码从 ac 文件中删除注释和字符串。我只会坚持对示例的评论。我有一个滑动窗口,所以我只有字符n
和n-1
在任何给定的时刻。我试图找出一种whiles
尽可能不使用嵌套的算法,但我需要一段时间来getchar
完成输入。我的第一个想法是 while through find when n=* and (n-1)=/
then while through until n=/ and (n-1)=*
,但考虑到这嵌套 whiles 我觉得它效率低下。如果必须的话,我可以这样做,但我想知道是否有人有更好的解决方案。
用一个循环编写的算法while
可能如下所示:
while ((c = getchar()) != EOF)
{
... // looking at the byte that was just read
if (...) // the symbol is not inside a comment
{
putchar(c);
}
}
Run Code Online (Sandbox Code Playgroud)
要确定输入是否char
属于注释,您可以使用状态机。在下面的例子中,它有4种状态;还有遍历到下一个状态的规则。
int state = 0;
int next_state;
while ((c = getchar()) != EOF)
{
switch (state)
{
case 0: next_state = (c == '/' ? 1 : 0); break;
case 1: next_state = (c == '*' ? 2 : c == '/' ? 1 : 0); break;
case 2: next_state = (c == '*' ? 3 : 2); break;
case 3: next_state = (c == '/' ? 0 : c == '*' ? 3 : 2); break;
default: next_state = state; // will never happen
}
if (state == 1 && next_state == 0)
{
putchar('/'); // for correct output when a slash is not followed by a star
}
if (state == 0 && next_state == 0)
{
putchar(c);
}
state = next_state;
}
Run Code Online (Sandbox Code Playgroud)
上面的例子非常简单:它不能/*
在非注释上下文(如 C 字符串)中正常工作;它不支持//
评论等。