字符串统计编程怎么写的

时间:2025-01-25 01:10:53 游戏攻略

统计字符串中各个数字、空白字符以及其他所有字符出现的次数,可以使用以下几种方法:

方法一:使用C语言

```c

include

include

int main() {

int ch, space = 0, other = 0, i;

int num = {0};

while ((ch = getchar()) != EOF) {

if (isspace(ch)) {

space++;

} else if (ch >= '0' && ch <= '9') {

num[ch - '0']++;

} else {

other++;

}

}

printf("space = %d\n", space);

printf("other = %d\n", other);

for (i = 0; i < 10; i++) {

if (num[i] > 0) {

printf("%d: %d\n", i, num[i]);

}

}

return 0;

}

```

方法二:使用C语言和fgets

```c

include

include

define M 1024

void main() {

char str[M];

fgets(str, M, stdin);

int space = 0, letter = 0, num = 0, other = 0;

for (int i = 0; i < strlen(str); i++) {

if (str[i] == ' ') {

space++;

} else if (str[i] >= '0' && str[i] <= '9') {

num++;

} else {

other++;

}

}

printf("空格的个数为: %d\n", space);

printf("英文字母的个数为: %d\n", letter);

printf("数字的个数为: %d\n", num);

printf("其他字符的个数为: %d\n", other);

}

```

方法三:使用C语言和getchar

```c

include

void main() {

char a, b;

int count1 = 0;

printf("输入字符串: ");

do {

a = getchar();

if (a != '\n') {

count1++;

}

} while (a != '\n');

printf("字符总数: %d\n", count1 - 1);

}

```

方法四:使用C语言和正则表达式

```c

include

include

int main() {

char str;

printf("输入字符串: ");

fgets(str, 1000, stdin);

int num = 0;

for (int i = 0; str[i] != '\0'; i++) {

if (isdigit(str[i])) {

num++;

}

}

printf("数字的个数为: %d\n", num);

return 0;

}

```

方法五:使用Java

```java

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

public class StrCount {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("请输入一串字符串:");

String line = sc.nextLine();

Map map = new HashMap<>();

for (char c : line.toCharArray()) {

if (Character.isDigit(c)) {

map.put(c, map.getOrDefault(c, 0) + 1);

}

}

for (Map.Entry entry : map.entrySet()) {

System.out.println(entry.getKey() + "(" + entry.getValue() + ")");

}

}

}

```

方法六:使用Python