我完全是初学者,我想做一个应用程序,对于作为命令行参数提供的每一个较低的驼峰大小写单词,都将打印出与snake大小写等价的单词。还将大字母转换成小字母,并在它们之间进行转换。
例子:

./coverter Iwant tobe famousAlready.

输出:
i_want
tobe
famous_already

我找到了一些代码,使字母变小,并在命令行中分别输出单词。但我不知道如何把它们组合在一起,如何在函数中吸引到单个字符?这可能吗?
#include <stdio.h>

int main (int argc, char* argv[]);
{
    printf("argc = %d\n", argc);

    for (int i = 0; i < argc; i++)
    {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
}

char change()
{
    char words[30];
    int ch;

    printf ("Give the words: ");

    int i=0;

    while ((ch=getchar()) != EOF)
    {
        slowko[i]=ch;
        if(isupper(slowko[i])) /* isupper, robi rzeczy - sprawdza czy */
                               /* litera z sekwencji jest duza */
        {
            slowko[i]=tolower(ch); /*zamien duzy znak na maly*/
            printf("_");
        }
        else if(slowko[i] == ' ')
        {
            printf("\n");
        }

        printf ("%c", slowko[i]);
        i++;
    }
}

最佳答案

从索引1开始的argv数组中有命令行参数。也许,这不是最优雅的解决方案,但它确实有效:

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

void print_snake_case(const char str[]){

    int i = 0;
    while (str[i] != '\0')
    {
        if(isupper((unsigned char) str[i])) /*isupper, robi rzeczy - sprawdza     czy     litera z sekwencji jest duza*/
        {
            const char ch = tolower((unsigned char) str[i]); /*zamien duzy znak na maly*/

            /*
               Different order of "_": it should be placed after
               the character in case it's at the beginning of the word.
               And before the character if it's not at the beginning.
            */
            if(i != 0)
            {
                printf("_");
                printf ("%c", ch);
            }
            else
            {
                printf ("%c", ch);
                printf("_");
            }
        }
        else
            printf ("%c", str[i]);


        i++;
    }

    printf("\n");
}

int main (int argc, char* argv[])
{
    for (int i = 1; i < argc; i++)
    {
        print_snake_case(argv[i]);
    }
}

输出:
$ ./converter Iwant tobe famousAlready
i_want
tobe
famous_already

关于c - C,将 Camel 文字变成蛇文字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52919818/

10-11 06:43
查看更多