【问题标题】:C, turning camel text into snake textC、把骆驼文字变成蛇文字
【发布时间】:2018-10-21 20:57:08
【问题描述】:

我完全是初学者,我想制作一个应用程序,对于作为命令行参数提供的每个较低的 camel case 单词将打印它的 snake case 等效项。还将大字母变成小字母并在它们之间生成"_"

示例:

./coverter Iwant tobe famousAlready.

输出:

i_want
tobe
famous_already

我找到了一些代码可以使字母变小,并在命令行中分别输出单词。但我不知道如何将它们放在一起,如何在函数 main 中诉诸单个字符?这甚至可能吗?

#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++;
    }
}

【问题讨论】:

  • 您在这里使用了两种输入方法:参数向量和带有getchar 的交互式流。根据问题陈述,不应使用流,而应为函数提供字符串参数。
  • 您的第一个测试用例与通常的定义不匹配。通常,插入下划线的唯一位置是在小写字母和大写字母之间。

标签: c arrays pointers


【解决方案1】:

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

#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

【讨论】:

  • 为什么是char change?为什么它的参数不是const char *?该函数最好称为print_snake_case 而不是change,因为后者的名称太不具体了。另外,在将可能已签名的 char 传递给 tolower 时,您会调用未定义的行为。
  • @RolandIllig “为什么要更改字符?” - 替换为无效
  • @RolandIllig “为什么它的参数不是 const char *?” - 它在函数内部进行了修改。但是 const 更好。固定。
  • @RolandIllig "该函数最好称为 print_snake_case 而不是 change" - 已修复
  • @RolandIllig “你在将一个可能有符号的字符传递给 tolower 时调用了未定义的行为”——我们能做些什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-21
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
相关资源
最近更新 更多