编写一个程序,由函数main和函数fun组成。函数fun(chars, int t)功能是:统计形参s所指字符串中''字符出现的次数,并存放在形参t所指的变量中,最后在主函数中输出
时间: 2024-05-08 09:19:48 浏览: 9
以下是C++语言的代码实现:
```C++
#include <iostream>
#include <cstring>
using namespace std;
void fun(char *chars, int *t) {
int count = 0;
for (int i = 0; i < strlen(chars); i++) {
if (chars[i] == '\'') {
count++;
}
}
*t = count; // 将计数器赋值给t所指的变量
}
int main() {
char str[] = "Hello, 'world'! How 'are' you?";
int count = 0;
fun(str, &count); // 调用函数fun,并将count的地址传递给形参t
cout << "The number of ' in the string is: " << count << endl;
return 0;
}
```
输出结果:
```
The number of ' in the string is: 4
```
说明:以上代码中,函数fun的形参使用指针类型,可以在函数内部修改实参的值,即将计数器count的值赋给形参t所指向的变量。在主函数中,将字符串和计数器count作为实参传递给函数fun,并输出统计结果。
相关问题
用C语言编写一个函数由实参传来一个字符统计字母,数字,空格和其他
下面是一个用C语言编写的函数,可以统计输入字符串中字母、数字、空格和其他字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(char *str, int *letters, int *digits, int *spaces, int *others) {
int i = 0;
char c;
while ((c = str[i++]) != '\0') {
if (isalpha(c)) {
(*letters)++;
} else if (isdigit(c)) {
(*digits)++;
} else if (isspace(c)) {
(*spaces)++;
} else {
(*others)++;
}
}
}
int main() {
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("Enter a string: ");
fgets(str, 100, stdin);
count_chars(str, &letters, &digits, &spaces, &others);
printf("Letters: %d\n", letters);
printf("Digits: %d\n", digits);
printf("Spaces: %d\n", spaces);
printf("Others: %d\n", others);
return 0;
}
```
在上面的代码中,`count_chars()` 函数接受一个字符串指针和四个整型指针作为参数,用来统计该字符串中字母、数字、空格和其他字符的个数。该函数使用了标准库函数 `isalpha()`、`isdigit()` 和 `isspace()` 来判断字符类型。
在 `main()` 函数中,先读入一个字符串,并将该字符串和四个整型变量的地址传递给 `count_chars()` 函数,最后输出各种字符的个数。
python编写一个统计函数,输入字符串,统计英文字符、数字和其它字符
可以使用Python的内置函数isalpha()、isdigit()和其他字符判断方法来实现。
以下是一个实现该功能的函数:
```python
def count_chars(s):
# 初始化计数器
count_alpha = 0
count_digit = 0
count_other = 0
# 遍历字符串
for c in s:
if c.isalpha(): # 判断是否为英文字符
count_alpha += 1
elif c.isdigit(): # 判断是否为数字
count_digit += 1
else:
count_other += 1 # 其他字符
# 返回计数结果
return count_alpha, count_digit, count_other
```
使用示例:
```python
s = "Hello, World! 123"
count_alpha, count_digit, count_other = count_chars(s)
print(f"英文字符:{count_alpha}")
print(f"数字:{count_digit}")
print(f"其他字符:{count_other}")
```
输出:
```
英文字符:10
数字:3
其他字符:4
```