java中统计跟“string”相同的字符串有多少个,(Str3.java) {“string”,“starting”,“string”,“street”,“soft”}count++
时间: 2023-09-21 15:09:52 浏览: 31
可以使用一个HashMap来记录每个字符串出现的次数,然后遍历数组,统计出现次数即可。
下面是代码实现:
```java
import java.util.HashMap;
public class Str3 {
public static void main(String[] args) {
String[] strs = {"string", "starting", "string", "street", "soft"};
HashMap<String, Integer> map = new HashMap<>();
for (String str : strs) {
if (map.containsKey(str)) {
map.put(str, map.get(str) + 1);
} else {
map.put(str, 1);
}
}
int count = map.getOrDefault("string", 0);
System.out.println("Count: " + count);
}
}
```
运行结果:
```
Count: 2
```
相关问题
java统计跟“string”相同的字符串有多少个,(Str3.java) {“string”,“starting”,“string”,“street”,“soft”}count++
可以使用Java中的HashMap来统计字符串出现的次数。具体实现如下:
```java
import java.util.HashMap;
public class Str3 {
public static void main(String[] args) {
String[] strings = {"string", "starting", "string", "street", "soft"};
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (String str : strings) {
if (map.containsKey(str)) {
map.put(str, map.get(str) + 1);
} else {
map.put(str, 1);
}
}
int count = map.get("string");
System.out.println("count: " + count);
}
}
```
运行结果为:
```
count: 2
```
说明字符串数组中有两个字符串与"string"相同。
统计跟“string”相同的字符串有多少个,(Str3.java) {“string”,“starting”,“string”,“street”,“soft”}count++
可以使用一个计数器变量,遍历字符串数组,判断每个字符串是否与目标字符串"string"相同,如果相同则计数器加1。最后输出计数器的值即可。
可以参考下面的代码实现:
```java
public class Str3 {
public static void main(String[] args) {
String[] arr = {"string", "starting", "string", "street", "soft"};
String target = "string";
int count = 0;
for (String str : arr) {
if (str.equals(target)) {
count++;
}
}
System.out.println("There are " + count + " strings that are the same as \"" + target + "\".");
}
}
```
输出结果为:
```
There are 2 strings that are the same as "string".
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)