整串为yeyeyeyeydddyeyey,子串为yey,确定子串在整串中出现的次数(用Java语言编写)
3条回答 默认 最新
CSDN专家-林老师 2021-06-08 09:42关注public class Demo { public static void main(String[] args) { // 定义俩个字符串 String shortStr = "yey"; String longStr = "yeyeyeyeydddyeyey"; // 调用searchCount方法 int count = searchCount(3, shortStr, longStr); // 输出字符串出现的次数 System.out.println("yey出现的次数是:" + count); } // 定义searchCount方法,来返回字符串出现的个数 public static int searchCount(int startIndex, String shortStr, String longStr) { // 将长字符串截取成从指定位置开始的字符串 longStr = longStr.substring(startIndex); // 定义一个count来存放字符串出现的次数 int count = 0; // 调用String类的indexOf(String str)方法,返回第一个相同字符串出现的下标 while (longStr.indexOf(shortStr) != -1) { // 如果存在相同字符串则次数加1 count++; // 调用String类的substring(int beginIndex)方法,获得第一个相同字符出现后的字符串 longStr = longStr.substring(longStr.indexOf(shortStr) + shortStr.length()); } // 返回次数 return count; } }如上,满意请采纳,谢谢!
本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 2无用