我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
public static int countSubstring(String subStr, String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.substring(i).startsWith(subStr)) {
count++;
}
}
return count;
}
其他回答
我有一个类似于Mladen的想法,但恰恰相反……
String s = "a.b.c.d";
int charCount = s.replaceAll("[^.]", "").length();
println(charCount);
试试下面的代码:
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);
}
}
你为什么要避开这个循环?我的意思是,如果不检查字符串的每一个字符,你就不能计算“numberOf”点,如果你调用任何函数,它都会以某种方式循环。这是字符串。Replace应该执行一个循环验证字符串是否出现,以便它可以替换每一个出现的字符串。
如果你试图减少资源使用,你不会这样做,因为你创建一个新的字符串只是为了计数点。
现在,如果我们讨论递归的“在这里输入代码”方法,有人说它会因为OutOfMemmoryException而失败,我想他忘记了StackOverflowException。
所以我的方法是这样的(我知道它像其他的,但是,这个问题需要循环):
public static int numberOf(String str,int c) {
int res=0;
if(str==null)
return res;
for(int i=0;i<str.length();i++)
if(c==str.charAt(i))
res++;
return res;
}
下面是一个没有循环的解决方案:
public static int countOccurrences(String haystack, char needle, int i){
return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}
System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));
嗯,有一个循环,但它是看不见的:-)
——约拿单
使用Java 8和HashMap,没有任何库来计数所有不同的字符:
private static void countChars(String string) {
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
string.chars().forEach(letter -> hm.put(letter, (hm.containsKey(letter) ? hm.get(letter) : 0) + 1));
hm.forEach((c, i) -> System.out.println(((char)c.intValue()) + ":" + i));
}