c语言读入一个字符串(字符串长度不超过50),判断该字符串中包含子串Bistu的个数
时间: 2025-01-13 08:05:42 浏览: 41
在C语言中,你可以使用`strchr()`函数配合循环来实现这个功能。`strchr()`函数可以在给定的字符串中查找指定字符第一次出现的位置。我们可以遍历整个输入字符串,并在每个位置检查是否包含子串"Bistu"。
以下是简单的步骤:
1. 首先声明一个计数器变量,例如`int count = 0`,用于存储子串出现的次数。
2. 使用`fgets()`函数读取用户输入的字符串,保证不超过50个字符(包括空格),并加上结束符'\0'。
3. 定义子串"Bistu"。
4. 使用一个`while`循环遍历整个输入字符串,从头开始,每次使用`strchr()`检查子串是否存在。如果找到,将计数器加一,并移动查找起点到下一个位置继续查找。
5. 循环结束后,`count`就是子串"Bistu"的出现次数。
下面是示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 50
int main() {
char input[MAX_LENGTH];
char substring[] = "Bistu";
int count = 0;
printf("请输入一个不超过50个字符的字符串: ");
fgets(input, sizeof(input), stdin); // 去掉换行符
input[strcspn(input, "\n")] = '\0'; // 移除fgets带来的换行符
while (input) {
char *found = strchr(input, substring[0]);
if (found != NULL && strncmp(found, substring, strlen(substring)) == 0) {
count++;
input = found + 1; // 移动查找起点
} else {
break;
}
}
printf("字符串 '%s' 中'Bistu' 子串出现了 %d 次.\n", input, count);
return 0;
}
```
阅读全文