亲,敢写完整的吗?
package com.oracle;
public class test01 {
public static void test01(){
String str=("dfghdshfrtdhgffdhfdhhtfnxsadgh");
int a = str.length()-str.replaceAll("f", "").length();
public static void main(String[] args) {
test01();
}
}
这只是一个静态方法,放类里就能用的,还要怎么完整……
外面的类也需要?
这个这个,初学者啊,很多东西都不是很懂的
追答额外提一下,用split比这个还要简单一些,不过replaceAll和split的参数都是正则表达式,如果你用那个需要把s处理一下,变成Pattern.quote(s),repalce的参数只是普通的字符串。
再者都没判断空值之类的东西,需要的话自己加吧
说实话吧,嗯,你那个代码没有看懂,额,我才学java2天!
追答无语了……
把要统计的字符串从源字符串中删除,然后算出长度差值,除以统计字符串长度,最终就是个数。
split那个是分割字符串成数组,简单说来说是"ababa"按"b"分割得到个长度为3个数组,全是"a",减1后就是"b"的个数,问题是如果按空字符串""分割得到长度为6的数组,第一个为空串,其余是那5个字母,所以需要先判断一下
public static void test01(){
System.out.println("输入字符串:");
Scanner sc=new Scanner(System.in);
String s=sc.next();
String str=(s);
int a = str.length()-str.replaceAll("f", "").length();
System.out.println("f"+"出现的次数是:"+a);
}
我是这么想的嘛,自己输入字符串,和需要匹配的单词,然后系统给出个数,然后我就不知道怎么写了,英雄,救命啊!
public class Test {
public static void main(String[] args) {
String src = "abcabcabc";
System.out.println("输入字符串:");
Scanner sc=new Scanner(System.in);
String s=sc.next();
int count = test(src, s);
System.out.println(src + "中" + s + "出现的次数是:" + count);
}
public static int test(String src, String s) {
return (src.length() - src.replace(s, "").length()) / s.length();
}
}