字符串重复字符统计代码
时间: 2023-04-03 16:04:51 浏览: 58
以下是一个简单的字符串重复字符统计代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int count[256] = {0};
int len, i;
printf("请输入一个字符串:");
scanf("%s", str);
len = strlen(str);
for(i = 0; i < len; i++)
{
count[str[i]]++;
}
printf("重复字符的统计结果如下:\n");
for(i = 0; i < 256; i++)
{
if(count[i] > 1)
{
printf("%c 出现了 %d 次\n", i, count[i]);
}
}
return 0;
}
```
以上代码可以统计一个字符串中出现次数大于1的字符及其出现次数。
相关问题
Java统计字符串重复次数
可以使用HashMap来统计字符串重复次数,具体实现如下:
```java
String str = "hello world";
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
System.out.println("每个字符出现的次数:");
for (char key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
```
上述代码将输出每个字符出现的次数,例如对于字符串 "hello world",输出结果如下:
每个字符出现的次数:
h:1
e:1
l:3
o:2
:1
w:1
r:1
d:1
其中,字符'l'出现的次数为3,字符'o'出现的次数为2,其余字符均只出现一次。
java 统计重复字符串
可以使用 HashMap 来实现统计重复字符串的功能。具体实现步骤如下:
1. 遍历字符串数组,将每个字符串作为 key 存入 HashMap 中,并将其 value 初始化为 1;
2. 如果在遍历过程中遇到相同的字符串,则将其对应的 value 值加 1;
3. 遍历完字符串数组后,遍历 HashMap,输出 value 值大于 1 的字符串及其出现次数。
以下是示例代码:
```java
public static void countDuplicateStrings(String[] strings) {
Map<String, Integer> map = new HashMap<>();
// 统计每个字符串出现的次数
for (String s : strings) {
map.put(s, map.getOrDefault(s, 0) + 1);
}
// 输出重复字符串及其出现次数
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " 出现了 " + entry.getValue() + " 次");
}
}
}
```
调用该方法并传入字符串数组即可统计重复字符串。例如:
```java
String[] strings = {"apple", "banana", "orange", "apple", "grape", "banana"};
countDuplicateStrings(strings);
```
输出结果:
```
apple 出现了 2 次
banana 出现了 2 次
```