1、用LEN和SUBSTITUTE函数配合计算。示例:假定A1="abcdacad",求a的个数。
公式=len(a1)-len(substitute(a1,"a",)) 这种方法的原理是:用原字符串长度减去删除指定字符后的字符串长度,得到指定字符的数量。
2、用SUMPRODUCT和MID函数计算。如上例,公式为:=SUMPRODUCT(N(MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1)="a"))
公式首先用MID函数将字符串分解为单个元素,再进行一一比对,最后用SUMPRODUCT函数汇总得到结果。
/** 返回一个字符串在另一个字符串中出现的次数
*
* */
public class StrTest {
public static int f(String s1,String s2){
int a = s1.length()
int b = s2.length()
int i = 0,sum = 0
while( i <= (b - a)){
if(s1.charAt(0) == s2.charAt(i)){
if(s2.substring(i, i + a ).equals(s1))
{i = i + a - 1
sum++
}
}
++i
}
return sum
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in)
System.out.println("输入子字符串")
String s1 = sc.next()
System.out.println("输入母字符串")
String s2 = sc.next()
System.out.println("子字符串在母字符串中出现的次数是:" + f(s1,s2))
}
}