统计跟“string”相同的字符串有多少个,(Str3.java) {“string”,“starting”,“string”,“street”,“soft”}count++
时间: 2023-09-21 07:06:50 浏览: 25
JAVA 统计字符串中中文,英文,数字,空格,特殊字符的个数
5星 · 资源好评率100%
可以使用一个计数器变量,遍历字符串数组,判断每个字符串是否与目标字符串"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".
```
阅读全文