获取一个字符串在另一个字符串中出现的次数。比如:获取“ab”在 “abkkcadkabkebfkabkskab” 中出现的次数21
package Java5.exer; import org.testng.annotations.Test; /** * @author test_2902059961@qq.com * @version v1.0 * @Date:2022/2/18 * @Description 获取一个字符串在另一个字符串中出现的次数。比如:获取“ab”在 “abkkcadkabkebfkabkskab” 中出现的次数21 */ public class JavaStringExer1 { public int isStringNumber(String str, String numStr) { if (str.length() >= numStr.length()) { if(str != null && numStr != null) { int total = 0; char[] strChar = str.toCharArray(); char[] numStrChar = numStr.toCharArray(); for (int i = 0; i < str.length(); i++) { if(strChar[i] == numStrChar[0]) { if(i < (strChar.length - numStr.length()) + 1) { for (int j = i+1, x = 1; x < numStr.length(); j++, x++) { if(strChar[j] == numStrChar[x]) { if(x == numStr.length() - 1) { total++; } } } } } } return total; } } return 0; } @Test public void test1() { String test = "abkkcadkabkebfkabkskab"; int num = isStringNumber(test, "bk"); System.out.println("次数为:" + num + "次"); } }