java中怎么判断字符串中包含字符个数
/*
* Email:97163017@qq.com
*/
public int countChar(String str,char ch) {
// 将字符串转换为字符数组
char[] chs = str.toCharArray();
// 定义变量count存储字符串出现次数
int count = 0;
for(int i = 0;i < chs.length;i++) {
if(chs[i] == ch) {
count++;
}
}
return count;
}
如果要知道字符个数,也就是字符串长度。直接调用length()方法即可。
绝对原创! 网上都是用indexOf方式,效率和内存性能低下!
采用正则表达式技术,简单实现:
public static void main(final String[] args) {
final String input = "This is captain's instruction!";
final int result = countInnerStr(input, "i");
System.out.println(String.format("Found: %d", result));
}
public static int countInnerStr(final String str, final String patternStr) {
int count = 0;
final Pattern r = Pattern.compile(patternStr);
final Matcher m = r.matcher(str);
while (m.find()) {
count++;
}
return count;
}
输出:
Found: 5
String s="asodad";
System.out.println(s.length());输出是6