我想编写一个程序来输出字符串的样式是帕斯卡大小写、驼峰大小写、蛇形大小写、烤肉串大小写,还是都不是。 在第一行,我们应该从输入中获取整数
n
。然后,在接下来的 n 行中,我们应该取一个整数k
,然后是每行中没有空格的字符串。 k 是字符串的大小。
以下是每种案例样式的示例:
pascal case => HelloWorld
camel case => helloWorld
snake case => hello_world
kebab case => hello-world
例如:输入:
3
11 masterShifu
12 master_shifu
12 MASTER_SHIFU
输出:
驼包
蛇壳
未定义的大小写样式
这个程序的问题是我不知道如何找到每个单词的第一个字母,因为两个不同的单词之间没有空格。这是我到目前为止写的:
#include <stdio.h>
#include <ctype.h>
int
main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int k;
scanf("%d ", &k);
char word[k];
gets(word[k]);
int count = 0;
if (isupper(word[0]) == 1) {
for (int i = 1; i < n; i++) {
if (isupper(word[i]) == 1) {
count++;
}
}
if (count == k)
printf("Undefined Case Style\n");
else
printf("PascalCase\n");
}
else {
int c = 0,
s = 0,
count = 0;
for (int i = 0; i < n; i++) {
if (word[i] == '-') {
c++;
printf("kebab-case\n");
break;
}
else if (word[i] == '_') // snake case
{
s++;
printf("snake_case\n");
break;
}
else if (isupper(word[i]) == 1) // camel case
{
count++;
printf("camelCase\n");
break;
}
}
if (c == 0 && s == 0)
printf("Undefined Case Style\n");
}
}
return 0;
}
我建议你遍历输入字符串
s
然后给定你已经建立的状态 found
确定当前字符 *s
是否对这种情况有效:
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
enum str_case {
CAMEL,
KEBAB,
PASCAL,
SNAKE,
UNDEFINED,
};
enum str_case str2str_case(const char *s) {
enum str_case found = isupper(*s++) ? PASCAL : UNDEFINED;
for(; *s; s++) {
if(*s == '-') {
if(found == KEBAB)
continue;
if(found == UNDEFINED) {
found = KEBAB;
continue;
}
return UNDEFINED;
}
if(*s == '_') {
if(found == SNAKE)
continue;
if(found == UNDEFINED) {
found = SNAKE;
continue;
}
return UNDEFINED;
}
if(isupper(*s)) {
if(found == CAMEL || found == PASCAL)
continue;
if(found == UNDEFINED) {
found = CAMEL;
continue;
}
return UNDEFINED;
}
if(!islower(*s))
return UNDEFINED;
}
return found;
}
int main(void) {
struct test {
char *input;
enum str_case expected;
} tests[] = {
{"helloWorld", CAMEL},
{"hello-world", KEBAB},
{"HelloWorld", PASCAL},
{"hello_world", SNAKE},
{"", UNDEFINED},
{"!", UNDEFINED},
{"A-b", UNDEFINED},
{"a_b-c", UNDEFINED},
};
for(struct test *t = tests; t < tests + sizeof tests / sizeof *tests; t++) {
enum str_case got = str2str_case(t->input);
if(t->expected != got) {
printf("fail: %s: expected %d but got %d\n", t->input, t->expected, got);
continue;
}
printf("ok\n");
}
}
这是输出:
ok
ok
ok
ok
ok
ok
ok
ok
然后我会用宏重构代码:
#define CHECK(p, p2, f) \
if((p)) {\
if((p2))\
continue;\
if(found == UNDEFINED) {\
found = (f);\
continue;\
}\
return UNDEFINED;\
}
函数变得简单:
enum str_case str2str_case(const char *s) {
enum str_case found = isupper(*s++) ? PASCAL : UNDEFINED;
for(; *s; s++) {
CHECK(*s == '-', found == KEBAB, KEBAB);
CHECK(*s == '_', found == SNAKE, SNAKE);
CHECK(isupper(*s), found == CAMEL|| found == PASCAL, CAMEL);
if(!islower(*s))
return UNDEFINED;
}
return found;
}
除了使用
fgets()
之外,您似乎在解析输入格式和生成预期的输出格式方面没有问题。