用C语言用简单的数组和不使用其他库和函数统计一个字符串中某个字符出现的次数,该字符串与单个字符均由用户输入,如字符串输入为:I am a handsome boy! 单个字符输入为a,则最后结果为3。
时间: 2024-12-15 17:17:00 浏览: 42
在C语言中,你可以使用一个简单的循环结构来统计给定字符串中特定字符的出现次数。以下是一个示例程序:
```c
#include <stdio.h>
#include <string.h> // 引入strlen函数来获取字符串长度
int main() {
char str[100], ch;
printf("请输入一个字符串: ");
fgets(str, sizeof(str), stdin); // 使用fgets读取整个行,包括换行符
str[strlen(str) - 1] = '\0'; // 删除末尾的换行符
printf("请输入要查找的字符: ");
scanf("%c", &ch);
int count = 0; // 初始化计数器
for (int i = 0; str[i] != '\0'; i++) { // 遍历字符串直到遇到结束符
if (str[i] == ch) {
count++; // 如果当前字符等于目标字符,计数器加一
}
}
printf("字符 '%c' 出现了 %d 次.\n", ch, count);
return 0;
}
```
这个程序首先让用户输入字符串和要查找的字符,然后遍历字符串,每遇到一次指定字符就增加计数器。最后输出该字符在字符串中出现的次数。
相关问题
c语言单个字符串数组查找字符串
可以使用strcmp函数来对单个字符串数组进行查找。
例如,假设我们有一个字符串数组str_array,包含了多个字符串,我们想要查找其中的某个字符串target_str,可以使用以下代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str_array[10][20] = {"hello", "world", "foo", "bar", "apple", "banana", "cat", "dog", "sun", "moon"};
char target_str[20] = "banana";
int i, found = 0;
for (i = 0; i < 10; i++) {
if (strcmp(str_array[i], target_str) == 0) {
found = 1;
break;
}
}
if (found) {
printf("The target string \"%s\" is found at index %d.\n", target_str, i);
} else {
printf("The target string \"%s\" is not found in the array.\n", target_str);
}
return 0;
}
```
以上代码中,我们使用了一个双重循环来遍历字符串数组中的每个字符串,并使用strcmp函数逐个比较字符串,查找目标字符串。如果找到了目标字符串,我们设置found标记为1,并使用break语句跳出循环。最后,我们根据found标记的值输出查找结果。
c语言单个字符串数组查找字符
要查找单个字符在一个字符串数组中的位置,可以使用字符串库中的函数`strchr()`。该函数的原型为:
```c
char *strchr(const char *str, int c);
```
其中,`str`是要查找的字符串,`c`是要查找的字符。该函数会在`str`中查找字符`c`第一次出现的位置,并返回该位置的指针。如果`c`没有在`str`中出现,则返回`NULL`。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char *str[] = {"apple", "banana", "cherry", "date"};
char c = 'e';
int i;
for (i = 0; i < 4; i++) {
char *p = strchr(str[i], c);
if (p != NULL) {
printf("Found '%c' in '%s' at position %ld\n", c, str[i], p - str[i] + 1);
}
}
return 0;
}
```
该程序定义了一个字符串数组`str`,并且要查找字符`'e'`在该数组中每个字符串中出现的位置。在循环中,使用`strchr()`函数查找字符`'e'`在当前字符串中出现的位置,如果找到了,则输出该字符串和字符在字符串中的位置。
输出结果为:
```
Found 'e' in 'apple' at position 5
Found 'e' in 'cherry' at position 4
Found 'e' in 'date' at position 2
```
阅读全文
相关推荐
















