c - 将重复出现的相邻字符替换为其他字符

标签 c

问题

如果您有两个重复出现的字符,您将在输入中指定,例如,您输入“*”,则当与“A”等其他字符相邻时,您将在每一行上替换“**”,如何你会这么做吗?

我想到使用数组来存储每个字符,并使用索引i遍历数组,检查是否arr[i] = arr[i+1]="* ",然后简单地替换它。

但是您将替换哪一个以及您如何确保以及如何替换它?由于之前“*”占用了两个索引,现在我们只用一个来替换它。

最佳答案

我明白你在问什么。在您的情况下,如果您有 "**",您希望将这 2 个字符替换为 'A'。这很容易做到。您只需循环遍历输入的每个字符,延迟对序列的评估,直到读取了 2 个字符为止(只需在循环结束时将 current 保存为 last 并使用 last 作为标志就足够了)

然后,如果current == lastlast == 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/

相关文章:

c - 一种更好的大数相加方法,Project Euler #13

c - 如何等待启动线程执行初始化代码

c - mex 文件和 C 文件之间的不同结果

c - 声明长度为 [x] 个字符的 Char 数组

c - 操作系统架构: Kernel and Standard Library interoperability

ios - 我可以将任务分配给 iOS 中的特定核心吗?

c++ - Tmax(0x7fffffff) 的一个奇怪问题,为什么 (!x) == x?

c++ - 关闭cin与C scanf同步的弊端

c - 从文件 (CSV) c 中高效读取和复制数据/字符串

c - C : STARTTLS via OpenSSL 上的 SMTP