代码-JavaSE-String-两个小练习(求子串出现的次数、求最大相同子串)
1 package ceshi.string; 2 3 public class Exercise { 4 public static void main(String[] args) { 5 String str = "nbaxljijeijonbaklajldanba"; 6 String subString = "nba"; 7 int count = getSubStringCount(str, subString); 8 System.out.println("count=" + count); 9 10 //练习2 11 String str2 = "nbajaldfjl"; 12 System.out.println(getMaxSubString(str, str2)); 13 } 14 15 /** 16 * 练习:获取子串"nba"在"nbaxljijeijonbaklajldanba"出现的次数 17 * 思路: 18 * 1,找到子串第一次出现的角标 19 * 2,从(该角标+子串长度)的位置开始,再次找子串出现的角标 20 * 3,重复以上步骤,直至不含子串 21 */ 22 private static int getSubStringCount(String str, String subString) { 23 int count = 0; 24 int index = 0; 25 while ((index = str.indexOf(subString, index)) != -1) { 26 count++; 27 index = index + subString.length(); 28 } 29 return count; 30 } 31 32 /** 33 * 问题:求2个字符串中出现的最长相同子串 34 * 思路: 35 * 1.确定短的字符串 36 * 2.取短字符串的不同长度的子串(先长后短) 37 * 3.查看长字符串中是否含有这些子串 38 */ 39 private static String getMaxSubString(String str1, String str2) { 40 //确定长度较短的字符串 41 String s1 = str1.length() > str2.length() ? str1 : str2; 42 String s2 = s1.equals(str1) ? str2 : str1; 43 44 int length=s2.length(); 45 46 for (int i = length; i >= 1; i--) {//i定义子串的长度 47 for (int j = 0; i + j <= length; j++) {//j定义子串的起始index 48 String s3=s2.substring(j,i+j);//包含头,不包含尾 49 if(s1.contains(s3)) 50 return s3; 51 } 52 } 53 return "没有相同的子串!"; 54 } 55 }