问题
如果您有两个重复出现的字符,您将在输入中指定,例如,您输入“*”,则当与“A”等其他字符相邻时,您将在每一行上替换“**”,如何你会这么做吗?
我想到使用数组来存储每个字符,并使用索引i
遍历数组,检查是否arr[i] = arr[i+1]="* "
,然后简单地替换它。
但是您将替换哪一个以及您如何确保以及如何替换它?由于之前“*”占用了两个索引,现在我们只用一个来替换它。
最佳答案
我明白你在问什么。在您的情况下,如果您有 "**"
,您希望将这 2 个字符替换为 'A'
。这很容易做到。您只需循环遍历输入的每个字符,延迟对序列的评估,直到读取了 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
或者使用'-'
代替'A'
进行不同的替换,
$ echo "There are two **** in the sky" | ./bin/replseqchar '*' -
There are two -- in the sky
关于c - 将重复出现的相邻字符替换为其他字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55318481/