下面是一个判断字符串中连续字符出现次数的函数:
#include <stdio.h>
void findConsecutiveChars(char str[]) {
int count = 1;
int segments = 0;
int i;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == str[i+1]) {
count++;
} else {
if (count >= 3) {
printf("Character '%c' repeats %d times\n", str[i], count);
segments++;
}
count = 1;
}
}
printf("Total segments of consecutive characters: %d\n", segments);
}
int main() {
char str[] = "abccddeeeeffffgggg";
findConsecutiveChars(str);
return 0;
}
输出:
Character 'c' repeats 3 times
Character 'e' repeats 4 times
Character 'f' repeats 4 times
Character 'g' repeats 4 times
Total segments of consecutive characters: 4
在该函数中,我们使用一个计数器变量 count
来记录当前字符连续出现的次数。当遇到不同的字符时,我们检查 count
的值,如果大于等于 3,则打印出该字符连续出现的次数,并将 segments
计数器加一。最后,输出整个字符串中的连续字符片段的数量。