static void outStrOvMun(String ss){ Map<String, Integer> map = new HashMap<String, Integer>() ; for (int i = 0; i < ss.length(); i++) { String s = ss.substring(i, i+1) ; if(!map.containsKey(s)) map.put(s, 1) ; else map.put(s, map.get(s)+ 1) ;
} for (String key : map.keySet()) { System.out.println(key+":"+map.get(key)); } }
简单一点就行吧public class Test { public static void main(String[] args) { String str = "你大舅你二舅都是你舅"; int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '你') count++; } System.out.println(count); } }
public static int getCountStr(String countStr,String traget){ Pattern pattern=Pattern.compile(countStr,Pattern.MULTILINE|Pattern.LITERAL); Matcher matcher=pattern.matcher(traget); int count=0; while(matcher.find()&&++count>=0); return count; }
Map<String, Integer> map = new HashMap<String, Integer>() ;
for (int i = 0; i < ss.length(); i++) {
String s = ss.substring(i, i+1) ;
if(!map.containsKey(s))
map.put(s, 1) ;
else
map.put(s, map.get(s)+ 1) ;
}
for (String key : map.keySet()) {
System.out.println(key+":"+map.get(key));
}
}
public static void main(String[] args) {
String str = "你大舅你二舅都是你舅";
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == '你')
count++;
}
System.out.println(count);
}
}
public static int getCountStr(String countStr,String traget){
Pattern pattern=Pattern.compile(countStr,Pattern.MULTILINE|Pattern.LITERAL);
Matcher matcher=pattern.matcher(traget);
int count=0;
while(matcher.find()&&++count>=0);
return count;
}
String str = "你大舅你二舅都是你舅";
int length = str.split("你").length;当length是 -1的时候表示没有 不等于-1的时候 length-1就是匹配的个数
int length = str.split("你").length;当length是 1的时候表示没有 不等于1的时候 length-1就是匹配的个数
String str = "你大舅你二舅都是你舅";
int length = str.split("你").length-1;length就是匹配的个数
Scanner scanner = new Scanner(System.in);
while(true) {
String temp;
if((temp = scanner.nextLine()).equals("bye")) {
System.out.println("ok! byebye");
break;
}
count(temp, "你");
}
}
/**
* 指定字符在输入字符串中出现的次数
* @param temp 输入字符
* @param appear 指定字符
*/
public static void count(String temp, String appear) {
int length = temp.length() - temp.replaceAll(appear, "").length();
System.out.println("字符[" + appear + "]出现的次数:" + length);
}
}测试输出:我号喜欢你
字符[你]出现的次数:1
你子啊地方是你你你
字符[你]出现的次数:4
String[] arr = str.split("你");
System.out.println(arr.length);// 输出2
str = "你妹你";
arr = str.split("你");
System.out.println(arr.length);// 输出依然是2
// arr : { "", "妹"}Java API文档中对split()的解释中有这么一句话:
Trailing empty strings are therefore not included in the resulting array.
所以当"你"出现在最后时并不能使得到的数组长度加1。
先判断一下判断最后一个是否是“你”:
如果最后一个不是“你”,则直接:int length = str.split("你").length-1;如果最后一个是“你”:int length = str.split("你").length;