编程实现:任意输入一个字符串,统计字符串中的数字个数和 字母个数
时间: 2023-05-23 09:04:32 浏览: 103
Python实现:
```python
string = input("请输入一个字符串:")
letter_count = 0
digit_count = 0
for i in string:
if i.isalpha():
letter_count += 1
elif i.isdigit():
digit_count += 1
print("字母个数为:", letter_count)
print("数字个数为:", digit_count)
```
Java实现:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
int letterCount = 0;
int digitCount = 0;
for (int i = 0; i < string.length(); i++) {
if (Character.isLetter(string.charAt(i))) {
letterCount++;
} else if (Character.isDigit(string.charAt(i))) {
digitCount++;
}
}
System.out.println("字母个数为:" + letterCount);
System.out.println("数字个数为:" + digitCount);
}
}
```
C++实现:
```c++
#include <iostream>
using namespace std;
int main() {
string s;
cout << "请输入一个字符串:";
getline(cin, s);
int letterCount = 0;
int digitCount = 0;
for (int i = 0; i < s.length(); i++) {
if (isalpha(s[i])) {
letterCount++;
} else if (isdigit(s[i])) {
digitCount++;
}
}
cout << "字母个数为:" << letterCount << endl;
cout << "数字个数为:" << digitCount << endl;
return 0;
}
```
阅读全文