如何使用Java函数查询一个字符串中某个子串出现的次数?
发布时间:2023-07-01 01:11:06
要使用Java函数来查询一个字符串中某个子串出现的次数,可以采用以下几个步骤:
1. 创建一个函数,传入两个参数:字符串和要查询的子串。
public static int countSubstring(String mainString, String subString) {
// count variable to keep track of the number of occurrences
int count = 0;
// logic to count the number of occurrences
// ...
// return the count
return count;
}
2. 在函数中,使用一个循环来遍历主字符串的每个字符,并根据子串的长度来判断是否能形成一个完整的子串。
public static int countSubstring(String mainString, String subString) {
// count variable to keep track of the number of occurrences
int count = 0;
// loop through the main string
for (int i = 0; i <= mainString.length() - subString.length(); i++) {
// check if the substring matches the current part of the main string
if (mainString.substring(i, i + subString.length()).equals(subString)) {
// increase the count if the substring is found
count++;
}
}
// return the count
return count;
}
3. 在循环中,使用substring()方法截取主字符串中与子串长度相等的子串,并通过equals()方法与子串进行比较,若相等,则增加计数器。
4. 循环结束后,返回计数器的值作为结果。
public class Main {
public static void main(String[] args) {
String mainString = "This is a test string. Test.";
String subString = "test";
int count = countSubstring(mainString.toLowerCase(), subString.toLowerCase());
System.out.println("Number of occurrences: " + count);
}
public static int countSubstring(String mainString, String subString) {
// count variable to keep track of the number of occurrences
int count = 0;
// loop through the main string
for (int i = 0; i <= mainString.length() - subString.length(); i++) {
// check if the substring matches the current part of the main string
if (mainString.substring(i, i + subString.length()).equals(subString)) {
// increase the count if the substring is found
count++;
}
}
// return the count
return count;
}
}
上述代码中,我们在main()函数中测试了一组示例输入。在实际使用时,可以根据需要修改主字符串和子串的值。
需要注意的是,上述代码是区分大小写的。如果希望不区分大小写,可以在比较子串和主字符串的时候,都将它们转换为小写或大写。这可以通过调用toLowerCase()或toUpperCase()方法实现。
