如果你有两个重复出现的字符,你将在输入中指定,例如,你输入“*”,你将在每一行上替换“**”,当与“A”之类的其他字符相邻时,你会怎么做那?
我想过使用一个数组来存储每一个字符,并使用索引i
遍历数组,检查是否arr[i] = arr[i+1]="*"
,并简单地替换它。
但是,您将替换哪一个,以及如何确定,以及如何更换它?由于之前两个索引被“*”占用,现在我们只用一个替换它。
我明白你在问什么。在你的情况下如果你有"**"
你想用'A'
替换这些2个字符。这很容易做到。您将简单地循环输入的每个字符,延迟对序列的评估,直到您读取2个字符(在循环结束时将current
保存为last
并使用last
作为标志就足够了)
然后,如果current == last
和last == find
字符,替换序列并获得下一个输入字符,否则,只输出last
字符。
一个简短的例子,它将find
的序列字符作为第一个参数(如果没有提供参数则使用'*'
)和repl
字符作为第二个参数(如果没有提供参数则使用'A'
)将是:
#include <stdio.h>
int main (int argc, char **argv) {
int c, /* current char */
find = argc > 1 ? *argv[1] : '*', /* sequential char to find */
repl = argc > 2 ? *argv[2] : 'A', /* replacement for seq chars */
last = 0; /* previous char */
while ((c = getchar()) != EOF) { /* read each char */
if (last) { /* is last set? */
if (c == last && last == find) {/* do we have sequence? */
putchar (repl); /* output replacement */
last = 0; /* set last 0 */
continue; /* go get next char */
}
else /* otherwise */
putchar (last); /* just output last */
}
last = c; /* set last = current */
}
if (last) /* if last wasn't zeroed */
putchar (last); /* just output final char */
return 0;
}
示例使用/输出
$ echo "There are two ** in the sky" | ./bin/replseqchar
There are two A in the sky
$ echo "There are two *** in the sky" | ./bin/replseqchar
There are two A* in the sky
$ echo "There are two **** in the sky" | ./bin/replseqchar
There are two AA in the sky
或使用qazxsw poi而不是qazxsw poi使用不同的替代品,
'-'