我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
试试下面的代码:
package com.java.test;
import java.util.HashMap;
import java.util.Map;
public class TestCuntstring {
public static void main(String[] args) {
String name = "Bissssmmayaa";
char[] ar = new char[name.length()];
for (int i = 0; i < name.length(); i++) {
ar[i] = name.charAt(i);
}
Map<Character, String> map=new HashMap<Character, String>();
for (int i = 0; i < ar.length; i++) {
int count=0;
for (int j = 0; j < ar.length; j++) {
if(ar[i]==ar[j]){
count++;
}
}
map.put(ar[i], count+" no of times");
}
System.out.println(map);
}
}
其他回答
public static int countOccurrences(String container, String content){
int lastIndex, currIndex = 0, occurrences = 0;
while(true) {
lastIndex = container.indexOf(content, currIndex);
if(lastIndex == -1) {
break;
}
currIndex = lastIndex + content.length();
occurrences++;
}
return occurrences;
}
可以在一行代码中使用split()函数
int noOccurence=string.split("#",-1).length-1;
试试这个方法:
StringTokenizer stOR = new StringTokenizer(someExpression, "||");
int orCount = stOR.countTokens()-1;
我看到过很多这样的花招。现在我不反对漂亮的技巧,但就我个人而言,我喜欢简单地调用那些意味着要做工作的方法,所以我创造了另一个答案。
注意,如果性能有问题,请使用Jon Skeet的答案。在我看来,这个更一般化,因此可读性稍强(当然,对于字符串和模式也可重用)。
public static int countOccurances(char c, String input) {
return countOccurancesOfPattern(Pattern.quote(Character.toString(c)), input);
}
public static int countOccurances(String s, String input) {
return countOccurancesOfPattern(Pattern.quote(s), input);
}
public static int countOccurancesOfPattern(String pattern, String input) {
Matcher m = Pattern.compile(pattern).matcher(input);
int count = 0;
while (m.find()) {
count++;
}
return count;
}
在java-8中,你也可以使用流来实现这一点。显然,在幕后有一个迭代,但您不必显式地编写它!
public static long countOccurences(String s, char c){
return s.chars().filter(ch -> ch == c).count();
}
countOccurences("a.b.c.d", '.'); //3
countOccurences("hello world", 'l'); //3