java查找字符串出现的次数
时间: 2023-11-16 11:05:06 浏览: 69
可以使用Java中的String类的方法count来查找一个字符串在另一个字符串中出现的次数。代码示例如下:
```
String str = "hello world, world is beautiful!";
int count = str.count("world");
System.out.println("The word 'world' appears " + count + " times in the string.");
```
输出结果为:
```
The word 'world' appears 2 times in the string.
```
相关问题
java查找字符串中重复字符
可以使用一个 HashMap 来记录每个字符出现的次数,然后遍历字符串,如果发现某个字符出现次数大于 1,则说明该字符是重复的。以下是 Java 代码示例:
```java
public class DuplicateCharInString {
public static void main(String[] args) {
String str = "Hello, World!";
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
int count = map.get(c);
map.put(c, count + 1);
} else {
map.put(c, 1);
}
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
System.out.println("Duplicate character: " + entry.getKey() + ", count: " + entry.getValue());
}
}
}
}
```
输出结果为:
```
Duplicate character: l, count: 3
Duplicate character: o, count: 2
Duplicate character: !, count: 1
Duplicate character: ,, count: 1
Duplicate character: e, count: 1
Duplicate character: H, count: 1
Duplicate character: W, count: 1
Duplicate character: r, count: 1
```
可以看到,字符串中重复的字符有:l、o。
用java统计字符串中特定字符串出现次数
好的,可以的。您可以使用Java中的字符串库以及循环语句来实现统计字符串中特定字符串出现次数的功能。以下是一个简单的示例代码:
```java
public static int countOccurrences(String text, String target) {
int count = 0;
int index = 0;
while ((index = text.indexOf(target, index)) != -1) {
index += target.length();
count++;
}
return count;
}
public static void main(String args[]) {
String text = "Java is a popular programming language, used for web development, mobile applications, and more.";
String target = "Java";
int count = countOccurrences(text, target);
System.out.println("The string \"" + target + "\" appears " + count + " times in the text.");
}
```
在这个例子中,`countOccurrences`函数接受两个参数,`text`表示要统计的字符串,`target`表示要查找的特定字符串。`while`循环中的代码找到目标字符串的位置,并使用`count`计数器更新出现次数。最后,该函数返回次数。在`main`函数中,我们提供了要搜索的字符串和目标字符串,并将结果打印到控制台上。