题解 | #统计字符#
统计字符
https://www.nowcoder.com/practice/539054b4c33b4776bc350155f7abd8f5
解题思路
- 遍历输入字符串的每个字符
- 使用条件判断或正则表达式判断字符类型:
- 英文字母:a-z, A-Z
- 空格:' '
- 数字:0-9
- 其他字符:除上述字符外的所有字符
- 分别计数并输出结果
代码
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
getline(cin, str);
int letters = 0, spaces = 0, digits = 0, others = 0;
for (char c : str) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
letters++;
} else if (c == ' ') {
spaces++;
} else if (c >= '0' && c <= '9') {
digits++;
} else {
others++;
}
}
cout << letters << endl;
cout << spaces << endl;
cout << digits << endl;
cout << others << endl;
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int letters = 0, spaces = 0, digits = 0, others = 0;
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
letters++;
} else if (Character.isSpaceChar(c)) {
spaces++;
} else if (Character.isDigit(c)) {
digits++;
} else {
others++;
}
}
System.out.println(letters);
System.out.println(spaces);
System.out.println(digits);
System.out.println(others);
}
}
s = input()
letters = sum(1 for c in s if c.isalpha())
spaces = sum(1 for c in s if c.isspace())
digits = sum(1 for c in s if c.isdigit())
others = len(s) - letters - spaces - digits
print(letters)
print(spaces)
print(digits)
print(others)
算法及复杂度
- 算法:字符串遍历
- 时间复杂度:
- 其中
为字符串长度
- 空间复杂度:
- 只使用常数额外空间