package day19;
/**
* @author khq
*
*/
public class StringDemo {
/**
* @param args
*/
public static void main(String[] args) {
String str1 = "djgjabcddjabcdfabcdnbgabcde";
String str2 = "abc";
//String str2 = "abcde";
//String str2 = "dj";
String str3 = "ascgjnbacdhg";
String str4 = "o";
int count = getSubStringNum(str1,str2);
System.out.println("SubStringNum: "+count);
String str = getMaxLenSubString(str3,str4);
System.out.println("MaxLenSubString: "+str);
}
//获取子串个数
public static int getSubStringNum(String str1,String str2)
{
String max=null,min=null;
int count = 0;
int index = 0;
if(str1.length()==str2.length())
{
if(str1.equals(str2))
{
count = 1;
}
else
{
count = -1;
}
}
else
{
//确定子串,长度较小者
max = (str1.length()>str2.length())?str1:str2;
min = (str1.length()<str2.length())?(str1):str2;
//考虑在字符串的起始,结尾部分的查到的可能性
index = max.indexOf(min);
if(index>=0)
{
count++;
}
else
{
count = -1; //找不到返回-1
}
//indeOf,返回第一次索引位置,注意不要为负,表示没有索引到
while(index>=0 && ((index+min.length())<(max.length())))
{
index = max.indexOf(min,index+min.length());
if(index>0){
count++;
}
else
break;
}
}
if(count==-1)
System.out.println("\""+min+"\""+" can't be found in "+"\""+max+"\"");
return count;
}
//获取两个字符串中的最大长度子串
public static String getMaxLenSubString(String str1,String str2)
{
//确定较短的字符串
String max = (str1.length()>=str2.length())?str1:str2;
String min = (max.equals(str1))?str2:str1;
for(int x=0;x<min.length();x++)
{
for(int y=0,z=min.length()-x;z!=min.length()+1;y++,z++)
{
String sub = min.substring(y, z);
if(max.contains(sub))
return sub;
}
}
System.out.println("两个子符串无公共子串");
return null;
}
}
字符串练习—获取子串的个数和最大长度子串
最新推荐文章于 2022-12-29 11:39:06 发布