编写一个函数,函数的参数为字符串,函数的功能是统计字符串中数字字符的个数。从键盘输入一串字符,利用这个函数求数字字符个数。
时间: 2024-05-16 07:16:38 浏览: 91
下面是 Python 代码实现:
```python
def count_digits(s):
"""
统计字符串中数字字符的个数
"""
count = 0
for c in s:
if c.isdigit():
count += 1
return count
if __name__ == '__main__':
s = input("请输入字符串:")
digits_count = count_digits(s)
print("数字字符的个数为:", digits_count)
```
函数 `count_digits` 用于统计字符串中数字字符的个数,其中参数 `s` 为输入的字符串。函数内部使用 `for` 循环遍历字符串,判断每个字符是否为数字字符,如果是则计数器 `count` 加 1。最后返回计数器的值。
在主程序中,使用 `input()` 函数从键盘读入一个字符串,然后调用 `count_digits` 函数求解数字字符的个数,并输出结果。
相关问题
编写一个函数,统计任意一串字符中数字字符的个数,并在主函数中调用此函数
在Python中,你可以编写一个名为`count_digits`的函数来完成这个任务。这个函数会接收一个字符串作为输入,然后遍历整个字符串,只计算其中的数字字符。下面是函数的实现:
```python
def count_digits(s):
digit_count = 0
for char in s:
if char.isdigit(): # 判断字符是否为数字
digit_count += 1
return digit_count
# 主函数(main function)
def main():
input_string = input("请输入一串字符:")
num_of_digits = count_digits(input_string)
print(f"字符串 '{input_string}' 中的数字字符有 {num_of_digits} 个.")
if __name__ == "__main__":
main()
```
当你运行这个程序并输入字符串后,它将返回该字符串中数字字符的数量。
c语言编写一个函数,统计一个输入字符串中字母、数字、空格和其他字符的个数
可以使用C语言中的字符函数库ctype.h中的函数来判断字符的类型。具体实现如下:
```c
#include <stdio.h>
#include <ctype.h>
void countChars(char *str, int *letters, int *digits, int *spaces, int *others) {
while (*str) {
if (isalpha(*str)) { // 判断字母
(*letters)++;
} else if (isdigit(*str)) { // 判断数字
(*digits)++;
} else if (isspace(*str)) { // 判断空格
(*spaces)++;
} else { // 其他字符
(*others)++;
}
str++; // 指针后移
}
}
int main() {
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入字符串:");
gets(str); // 读入字符串
countChars(str, &letters, &digits, &spaces, &others);
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
注意,上述代码使用了gets函数读入字符串,但是gets函数有安全性问题,可以使用fgets函数替代。同时,由于C语言中没有字符串类型,所以我们使用字符数组来表示字符串。