c语言判断s所指字符串是否为连续字符
时间: 2023-10-18 08:03:35 浏览: 33
以下是一个判断字符串是否为连续字符的C语言函数:
```c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool is_consecutive(char *s) {
int len = strlen(s);
if (len == 0) {
return false;
}
int i;
for (i = 1; i < len; i++) {
if (s[i] != s[i-1] + 1) {
return false;
}
}
return true;
}
int main() {
char str1[] = "abcde";
char str2[] = "abccde";
char str3[] = "";
printf("%s is consecutive: %d\n", str1, is_consecutive(str1));
printf("%s is consecutive: %d\n", str2, is_consecutive(str2));
printf("%s is consecutive: %d\n", str3, is_consecutive(str3));
return 0;
}
```
该函数首先判断字符串的长度,如果长度为0,则不可能为连续字符,直接返回false。然后从字符串的第二个字符开始,逐个判断当前字符是否等于前一个字符加1,如果不是则返回false。如果所有字符都符合条件,则说明该字符串为连续字符,返回true。
在main函数中,我们测试了3个字符串,其中第一个字符串"abcde"为连续字符,第二个字符串"abccde"不是连续字符,第三个字符串为长度为0的空字符串,也不是连续字符。运行结果如下:
```
abcde is consecutive: 1
abccde is consecutive: 0
is consecutive: 0
```