我一直在试图弄清楚如何使数组中的某些字符串字母全部输入为小写字母,并输出一个下划线(即“ first_last”),并在它们之间加一个空格并将每个开头字母都大写(即“第一倒数”)。

任何有用的想法表示赞赏

这是我到目前为止的内容:

#include <stdio.h>
#define SIZE 30

int main()
{
    char string1(SIZE); //reserve a name of up to 29 characters

    //read characters from input into array string 1
    printf("%s", "Enter a name:);
    scanf("%29s", string1);
}

最佳答案

您可以按字符处理字符串并修改相关字符,例如:

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

// Capitalise based on your specs.

static void cap(char *str) {
    // No actions for empty string.

    if (*str == '\0') return;

    // Always upper first character.

    str[0] = toupper(str[0]);

    // Check all but last character (ignore trailing '_').

    for (size_t i = 1, count = strlen(str) - 1; i < count; ++i) {
        // If underscore, make space and upper next character.

        if (str[i] == '_') {
            str[i] = ' ';
            str[i+1] = toupper(str[i+1]);
        }
    }
}

// Test driver to do all arguments.

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; ++i) {
        printf("'%s'", argv[i]);
        cap(argv[i]);
        printf("-> '%s'\n", argv[i]);
    }
}


您可能想要处理极端情况,但是由于您尚未为它们指定所需的行为,因此我只是将它们留给读者作为进一步的练习。要考虑的事情是:


如何使用multiple____underscores处理字符串;
如何在字符串末尾处理_
如果不带小写字母,如何处理_;和
我可能没有想到的其他事情:-)




这是一个示例运行,因此您可以看到它的运行情况:

pax$ testprog first_second one one_two
'first_second'-> 'First Second'
'one'-> 'One'
'one_two'-> 'One Two'

关于c - 将C中的字符串中的特定字母大写,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53623892/

10-09 23:01
查看更多