【问题标题】:Replacing one and more spaces, with exactly ONE new line.用一个新行替换一个或多个空格。
【发布时间】:2017-05-10 18:33:01
【问题描述】:

我是练习代码。问题是,用新行替换输入中的空间。

我是这样写的:

int input;

while((input = getchar()) != EOF)
{
    if (input == ' ')
    {
        input = '\n';

    }

    putchar(input);

}

但我不知道如何使它将多个空格更改为恰好一个新行。我有一个想法,制作类似缓冲区变量(例如 int 缓冲区)并在其中存储空间,然后在输入后检查前一个字符是否为空间,但我不知道如何使其工作:P

【问题讨论】:

  • 什么?你有你的代码,为什么你对它不满意?你想让他们全部消失还是什么?
  • 添加一个标志,表明它已经被替换过一次。真的,简单的逻辑。
  • @gsamaras OP 想要s/\s+/$/
  • @gsamaras 是的,我希望所有这些都消失 :P 当我创建多个空格时,我的代码会出现问题,并且我希望我的单词或字符(没关系,只需输入)低于另一个:P
  • 尝试一个状态机,三种状态:读取一个空格;阅读空间以外的东西;阅读EOF。 ...

标签: c


【解决方案1】:
int input, last_was_space = 0;    
while((input = getchar()) != EOF)
{
    if(input == ' ')
    {
        last_was_space = 1;
    }
    else
    {
        if(last_was_space)
        {
            last_was_space = 0;
            putchar('\n');
        }

        putchar(input);
    }
}

【讨论】:

  • @MaciejMakulec 你不明白什么?我很乐意向你解释
  • 如果其他逻辑,我无法相处:P
【解决方案2】:

使用 this 代替 if 语句:

if(input == ' ') {
    while (input == ' ')
    {
        input = getchar();
    }
    putchar('\n');
}

【讨论】:

  • 停止删除和转发您的答案!如果您想修复您的代码,请在适当的位置对其进行编辑,或在发布之前对其进行测试。你可以在这里测试你的代码:ideone.com
  • 仍然不对:输入"one two" 产生"onet\nwo"
【解决方案3】:

也许这对你有用,尽管在输入结束或输入第一个非空格字符之前不会显示换行符。

int input = 0;
int previous = 0;

while((input = getchar()) != EOF)
{
    if (input != ' ')
    {
        if (previous == ' ')
        {
            putchar('\n');
        }
        putchar(input);
    }

    previous = input;
}

if (input == ' ')
{
    putchar('\n');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 2012-06-04
    • 2013-05-30
    • 2013-07-03
    相关资源
    最近更新 更多