2024-10-12 07:44:03
/*
* 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()方法即可。
2024-10-12 07:01:16
绝对原创! 网上都是用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
2024-10-12 07:07:17