我是一个完全的初学者,我想做一个应用程序,对于作为命令行参数提供的每个 camel case 小写单词,它将打印它的 snake case 等效项。还将大字母变成小字母,并在它们之间进行"_"
。
示例:
./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++;
}
}
答案 0 :(得分:0)
您在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