You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用getchar()在C语言中从段落移除单词bus?

How to Remove the Word "bus" Using getchar()

Got it, let’s break down how to solve this. Since getchar() reads one character at a time, we need to track the last few characters we’ve seen to detect when the sequence "bus" comes up. Here’s a straightforward implementation:

Approach

  • We’ll use a small buffer to keep track of the last two characters we’ve read.
  • For each new character, we check if combining it with the last two forms the word "bus".
  • If we find the sequence, we skip outputting those three characters and reset our buffer.
  • If not, we output the oldest character in the buffer, then shift the buffer to make room for the new character.
  • After input ends, we output any remaining characters in the buffer that weren’t part of a "bus" sequence.

Complete Code

#include <stdio.h>

int main() {
    char prev2 = '\0';  // Stores the character before the previous one
    char prev1 = '\0';  // Stores the previous character
    char current;

    while ((current = getchar()) != EOF) {
        // Check if we've found the "bus" sequence
        if (prev2 == 'b' && prev1 == 'u' && current == 's') {
            // Reset buffer to avoid false matches with leftover characters
            prev2 = '\0';
            prev1 = '\0';
        } else {
            // Output the oldest valid character
            if (prev2 != '\0') {
                putchar(prev2);
            }
            // Shift the buffer to track the most recent two characters
            prev2 = prev1;
            prev1 = current;
        }
    }

    // Output any remaining characters in the buffer after EOF
    if (prev2 != '\0') {
        putchar(prev2);
    }
    if (prev1 != '\0') {
        putchar(prev1);
    }

    return 0;
}

How It Works

  • Buffer Setup: We start with prev2 and prev1 set to '\0' (null character) because they don’t hold valid input yet.
  • Input Loop: For every character we read:
    • We check if the last three characters form "bus". If yes, we reset the buffer so those characters aren’t printed.
    • If not, we print the oldest character (if it’s valid), then update the buffer to keep track of the latest two characters.
  • Final Cleanup: After hitting EOF, we print any leftover characters in the buffer—these are characters that didn’t end up being part of a "bus" sequence.

Quick Test

If you input The bus goes by the bus stop, the output will be The goes by the stop (the spaces around "bus" stay intact since we’re only removing the word itself).

内容的提问来源于stack exchange,提问作者Rashad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:41:33