C语言快速判断字符串中是否只有一个'*'字符
可以使用循环遍历字符串,每次遇到''时,判断前面是否已经出现过'',如果出现过,则说明字符串中有多个'',直接返回false;否则,将标志位设置为已出现过'',继续往后遍历。最后,如果只出现过一次'*',则返回true。
示例代码如下:
#include <stdio.h>
#include <stdbool.h>
bool checkStar(char *str) {
bool flag = false; // 标志位,记录是否出现过'*'
while (*str != '\0') {
if (*str == '*') {
if (flag) {
return false; // 已经出现过'*',返回false
}
flag = true; // 设置标志位
}
str++;
}
return flag; // 如果只出现过一次'*',返回true
}
int main() {
char str1[] = "hello*world";
char str2[] = "he*llo*world";
char str3[] = "hello world";
printf("%d\n", checkStar(str1)); // 输出1
printf("%d\n", checkStar(str2)); // 输出0
printf("%d\n", checkStar(str3)); // 输出0
return 0;
}
原文地址: https://www.cveoy.top/t/topic/nf8I 著作权归作者所有。请勿转载和采集!