首页 > 解决方案 > c 中字符串首字母的大写 - 用 110 个字符编写 myprintf 函数

问题描述

我需要创建一个my_printf函数,它接受一个字符串,仅将字符串的第一个字母大写(即使之前有空格),然后执行一个 \n,全部在 110 个字符以下(不包括空格/制表符)。

我只能在“TO BE DONE START”和“TO BE DONE END”注释之间修改函数。

这是我到目前为止写的代码:我唯一遇到的问题是在输出中它没有大写字母“l”的“看起来不错:)”在 \t 之后,我不知道如何在不超过此代码中 110 个字符的最大限制器的情况下,实现不在字符串位置 q[0] 中的字符的大写;我知道它需要一个循环,但我似乎总是超出限制。

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void my_printf(char*p){
    char s[strlen(p)+1], *q=s;
    strcpy(s,p);

    /* TO BE DONE START */
    q[0]=toupper(q[0]);
    putchar(q[0]);
    for(*q=1;*q!='\0';++q) {
         putchar(*q);
    }
    putchar('\n');

    /* TO BE DONE END */
}

int main(){
    my_printf("hello world!");
    my_printf("How are you?");
    my_printf("i\'m OK, and you?");
    my_printf("1, 2, 3, testing ...");
    my_printf("\t  looks OK :-)");
    my_printf("bye bye!");
    return 0;
}

我需要帮助以使此代码尽可能短,这是所需的输出:

 Hello world!
 How are you?
 I'm OK, and you?
 1, 2, 3, testing …
            Looks OK :-)
 Bye bye!

而我的是:

 Hello world!
 How are you?
 I'm OK, and you?
 1, 2, 3, testing …
            looks OK :-)
 Bye bye!

标签: ccapitalization

解决方案


您可以使用该isspace功能 - 例如:

/* TO BE DONE START */
while (isspace(*q)) putchar(*q++);
for(*q = toupper(*q); *q; ) putchar(*q++);
putchar('\n');
/* TO BE DONE END */

推荐阅读