在一个字符串中查找子字符串出现的次数(两种方法)(遍历查找和切割判断)

xiaoxiao2021-02-28  40

/** * 思路:开始找,如果返回-1,结束程序 * 否则,计数+1,再继续从新的位置开始找,直到找不到 */ String str = "www.baidu.com/www.sina.com"; String subStr = "www"; int count = 0; //记录找到的索引 int i = 0; while(true) { if(str.indexOf(subStr, i) == -1) { //找不到,跳出来 break; }else { //找到,计数 count ++; //更新查找索引值,继续找 i = str.indexOf(subStr, i)+1; } } System.out.println(subStr+"在"+str+"中出现的次数:"+count);                 /** * 思路二:使用子串来切割父串,根据结果数组长度获取次数 * 考虑特殊情况--> 子串在末尾,要给截取结果数组长度加1 */ String str = "www.baidu.com/www.sina.com"; String subStr = "www"; int count = 0; String[] arr = str.split(subStr); int len = arr.length; if(str.endsWith(subStr)) { //如果子串在末尾 len ++; } count = len - 1; System.out.println(subStr+"\n在"+str+"中出现的次数:"+count);

转载请注明原文地址: https://www.6miu.com/read-2624508.html

最新回复(0)