1. 程式人生 > >Java 獲取指定字符串出現的次數

Java 獲取指定字符串出現的次數

索引 出現 color 一次 pat .net 老師 logs tag

Java中 獲取指定字符串在另一個字符串中出現的次數

方式一

/**
 * @param args
 */
public static void main(String[] args) {

    String srcText = "Hello World";
    String findText = "e";
    int num = appearNumber(srcText, findText);
    System.out.println(num);
}

/**
 * 獲取指定字符串出現的次數
 * 
 * @param srcText 源字符串
 * @param findText 要查找的字符串
 * @return
*/
public static int appearNumber(String srcText, String findText) { int count = 0; Pattern p = Pattern.compile(findText); Matcher m = p.matcher(srcText); while (m.find()) { count++; } return count; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

方式二

/**
 * @param args
 */
public static void main(String[] args) {

    String srcText = "Hello World";
    String findText = "e";
    int num = appearNumber(srcText, findText);
    System.out.println(num);
}


/**
 * public int indexOf(int ch, int fromIndex)
 * 返回在此字符串中第一次出現指定字符處的索引,從指定的索引開始搜索
 * 
 * @param
srcText * @param findText * @return */
public static int appearNumber(String srcText, String findText) { int count = 0; int index = 0; while ((index = srcText.indexOf(findText, index)) != -1) { index = index + findText.length(); count++; } return count; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

作者:itmyhome

再分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!希望你也加入到我們人工智能的隊伍中來!https://www.cnblogs.com/captainbed

Java 獲取指定字符串出現的次數