package com.itheima;
public class GetSub {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
String str = "abcd";
int num = 3;
String[] ss=getSub(str,num);
for(String s : ss)
System.out.println(s);
}
public static String[] getSub(String str,int sublength){
String[] s = new String[]{};//用于保存字串
int count = 0;
int len = str.length();
if (sublength>len || sublength<=0)
return s;//如果子串长度大于字符串长度,则不会有满足要求的子串
else{
int start = 0;
int startPos = 0;
s=new String[C(sublength,len)];
while((str.length() - start) >= sublength){
count++;//字串数目
String newStr = "";
String subStr = str.substring(start,start+1) + str.substring(startPos+1, startPos+sublength-1);
for(int i = sublength;i < str.length();i++){
newStr = (String)(subStr + str.charAt(i));
s[count++] = newStr;
}
startPos++;
if((str.length()-startPos) < sublength){
start++ ;
}
}
}
return s;
}
public static int C(int m,int n){
int c=1;
int k=1;
for (int i=1;i<=m;i++){
c=c*(n+1-i);
k=k*i;
}
return (c/k);
}
}
运行提示我:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at com.itheima.GetSub.getSub(GetSub.java:30)
at com.itheima.GetSub.main(GetSub.java:9)
|