【问题标题】:Print a string char by char without spaces逐字符打印字符串,不带空格
【发布时间】:2019-10-15 17:42:35
【问题描述】:

在我的作业问题中,我的老师希望我们编写一个程序,该程序将在新行上逐个字符地打印字符串,但会忽略空格并在同一行上打印重复的字符。因此,例如按字符打印“Hello World”字符将返回

H
e
ll
o
W
o
r
l
d

我已经能够让我的代码逐个字符地打印字符串,但我无法让它在同一行打印重复项或忽略空格。我看过其他一些类似的问题,似乎这不是一件容易的事。

#include <stdio.h>

void print_string(const char instring[]);

int main(void)
{
    print_string("Hello World");
    return 0;
}

void print_string(const char *instring)
{
        while(*instring!='\0')
    {
        printf("%c\n",*instring++);
    }
    return;
}

这将像这样返回每个字母

H
e
l
l
o

W
o
r
l
d

但不是按照理想的安排。我曾考虑过实现一个 do while 循环来忽略空格,但至于在同一行上打印重复的字母,我感到很困惑。此外,如果您想知道我为什么要使用指针,我们之前的作业部分是使用指针算术打印字符串的长度。不确定在没有指针的情况下是否会更容易。

【问题讨论】:

  • 如果你对每个角色都做同样的事情,那是行不通的。你必须以某种方式对不同的角色有不同的行为。继续努力!
  • 你有什么办法解决这个问题?空间要求微不足道。 if(char is space) skip。对于另一个要求,有多种方法可以做到。你可以有一个缓冲区while (thisChar eq lastChar) addToBuffer(thisChar),或者只是跟踪一个指向重复字符开头/结尾的指针并打印该子字符串。

标签: c string pointers printf


【解决方案1】:

在您的循环while(*instring!='\0') 中,您必须有另一个循环来检查当前字符之后的字符。如果它是空格,您还必须跳过该字符。例如:

    while(*instring!='\0') {
        if (isspace(*instring)) {
            instring++;
        } else {
            printf("%c",*instring);
            int i= 1;
            while (*instring == *(instring+i)) {
                printf("%c",*(instring+i));
                i++;
            }
            printf("\n");
            instring += i;
        }
    }

【讨论】:

  • 哦,谢谢。没想到这么详细的回答。你真的在重复字符部分帮助了我。谢谢,你已经清理了很多。
  • 告诉你的老师你有帮助,是的,@AjayBrahmakshatriya,你是对的。通常我只在处理作业时提供线索。今天,我觉得写线索比提供几行代码更辛苦……
【解决方案2】:

您可以有一个指向前一个字符的指针,并使用它来找出何时打印换行符。此外,您需要在打印当前字符之前检查空格。喜欢:

#include <stdio.h>

void print_string(const char instring[]);

int main(void)
{
    print_string("Hello World");
    return 0;
}

void print_string(const char *instring)
{
    const char *p = NULL;
    while(*instring!='\0')
    {
        if (p != NULL && *instring != *p && *instring != ' ') printf("\n");
        if (*instring != ' ') printf("%c",*instring);
        p = instring++;
    }
    printf("\n");
    return;
}

输出:

H
e
ll
o
W
o
r
l
d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-25
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    相关资源
    最近更新 更多