我正在尝试计算用户输入的字符串中的循环数和空行数。所以我是这样做的:
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void) {
int i, lines, loopF = 0, loopW = 0, loopDW = 0, empty = 0;
char *p, str[200];
const char test[10] = "while";
char *f;
printf("Enter a string. Ctrl+Z for exit.\n");
while (fgets(str, 200, stdin) != NULL) {
if (f = strstr(str, test)) { //first way
loopW++;
}
for (i = 0; i < strlen(str); i++) {
// count loops
if (str[i] == 'f' && str[i + 1] == 'o' && str[i + 2] == 'r') {
loopF++;
}
if (str[i] == 'w' && str[i + 1] == 'h' && str[i + 2] == 'i'
&& str[i + 3] == 'l' && str[i + 4] == 'e') { // second way
loopW++;
}
if (str[i] == 'd' && str[i + 1] == 'o') {
loopDW++;
if (loopDW >= 1)
loopW--;
}
}
// count empty lines
p = str;
lines = 0;
while (*p != '\n') {
if (*p != ' ') {
lines = 1;
}
p++;
}
if (!lines) {
empty++;
lines = 0;
}
}
printf("---------------------\n");
printf(" Empty lines: %d \n\n", empty);
printf(" Number of loops:\n");
printf(" For: %d \n", loopF);
printf(" While: %d \n", loopW);
printf(" Do/While: %d \n", loopDW);
printf("---------------------\n");
return 0;
}
我只用了两种方法来测试“while”,但是当用户键入“whilethis”或“thiswhile”时,它会计算它(这不是我想要的)。我想只计算一段时间(一个循环)而不是其他符号,但我不知道该怎么做。同样适用于 do/while 和 for 循环。这里有什么帮助吗? :)
最佳答案
正确的解决方案还需要处理字符串和注释
print("I have no for() loops")
/* commented out for() loop */
char* c = "for()\"loop\\";
如果您不关心这个,并且真的想使用纯 C,我会推荐“strtok”函数,它使用定界符将字符串拆分为单词(在您的情况下,这基本上是所有非字母数字符号——空格、方括号、逗号等)。然后一旦你有了单词,你就可以用“do”、“while”或“for”来 strcmp()
关于计算一个词被使用了多少次。 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41469694/