Java中,如何获取指定字符串在另一个字符串中出现的次数呢?
例如,获取keyword在srcText中出现的次数?
方式一:
- /**
- *
- * The number of occurrences of find keyword in srcText
- *
- * @param srcText
- * @param keyword
- * @return
- */
- public static int findStr1(String srcText, String keyword) {
- int count = 0;
- int leng = srcText.length();
- int j = 0;
- for (int i = 0; i < leng; i++) {
- if (srcText.charAt(i) == keyword.charAt(j)) {
- j++;
- if (j == keyword.length()) {
- count++;
- j = 0;
- }
- } else {
- i = i - j;// should rollback when not match
- j = 0;
- }
- }
- return count;
- }
方式二:
- public static int findStr2(String srcText, String keyword) {
- int count = 0;
- Pattern p = Pattern.compile(keyword);
- Matcher m = p.matcher(srcText);
- while (m.find()) {
- count++;
- }
- return count;
- }
方式三:
- public static int findStr3(String srcText, String keyword) {
- return findStr(srcText, keyword, 0);
- }
- public static int findStr(String srcText, String keyWord, int pos) {
- int i, j, k = 0;
- i = pos;
- j = 0;
- while (i < srcText.length() && j < keyWord.length()) {
- if (srcText.charAt(i) == keyWord.charAt(j)) {
- ++i;
- ++j;
- if (j == keyWord.length()) {
- k = k + 1;// k++
- j = 0;
- }
- } else {
- i = i - j + 1;
- j = 0;
- }
- }
- return k;
- }