另一个入门问题。
int counterConstant;
int x;
for(x = 0; x<20; x++){
if("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSVWXYZ".IndexOf(tempString[x]) >= 0){
counterConsonant++;
}
}
但是我得到一个错误:
"error: member reference base type 'char [42]' is not a structure or union"
还有其他方法吗?
(我在 for
中执行此操作,它检查 string
上的每个 char
。)
最佳答案
C 中没有对象,因此没有“方法”,您不能对字符串文字调用 IndexOf
。字符串只不过是 C 语言中的字符数组。
考虑到这一点,让我们看看如何实际循环遍历字符串的字符:
for (const char *p = tempString; *p != '\0'; ++p) {
/* loop body */
char c = *p; // *p is the current letter
}
这将创建一个指向字符串第一个元素的指针,然后循环遍历以下所有字符,如果你真的更喜欢使用索引,你可以这样做
for (size_t i = 0, len = strlen(tempString); i < len; ++i) {
char c = tempString[i];
}
就检查每个字母的辅音而言,您可以编写一个辅助函数
int is_consonant(char c) {
c = tolower(c); // #include <ctype.h>
if (!isalpha(c)) return 0; // if not a letter, return false
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return 0;
default:
return 1;
}
}
现在回到你的循环,使用这个函数来检查每个字符。
int consonant_count = 0; // the =0 is important!
for (const char *p = tempString; *p != '\0'; ++p) {
if (is_consonant(*p)) {
++consonant_count;
}
}
如果不初始化为 0,consonant_count
的初始值是不可预测的,所以一定要这样做。
关于计算字符串中辅音的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28269324/