class StringTest
{
public static void sop(String str)
{
System.out.println(str);
}
public static void main(String[] args)
{
//String s = " afdf d ";
//sop("("+s+")");
//sop("("+myTrim(s)+")");
//String s = "abccdeffcc";
//sop("("+s+")");
//sop("("+reverseString(s)+")");
//sop("("+reverseString(s,0,4)+")");
//sop("count:"+getSubCount(s, "cc"));
//sop("count:"+getSubCount_2(s, "cc"));
String s1 = "abcwerthelloyuiodef";
String s2 = "cvhellobnm";
sop(getMaxSubString(s2, s1));
}
//去除字符串两端的空格
public static String myTrim(String str)
{
int start=0,end=str.length()-1;
while(start<=end&&str.charAt(start)==' ')
start++;
while(start<=end&&str.charAt(end)==' ')
end--;
return str.substring(start,end+1);
}
//将字符串反转
public static String reverseString(String s,int start,int end)
{
char arr[] = s.toCharArray();
reverse(arr,start,end);
return new String(arr);
}
public static String reverseString(String s)
{
return reverseString(s, 0, s.length());
}
private static void reverse(char arr[],int x,int y)
{
for(int start=x,end=y-1;start<end;start++,end--)
{
swap(arr,start,end);
}
}
private static void swap(char arr[],int start,int end)
{
char tmp;
tmp = arr[start];
arr[start] = arr[end];
arr[end] = tmp;
}
//获取字串个数
public static int getSubCount(String s,String sub)
{
int count = 0;
int index =0;
while((index=s.indexOf(sub))!=-1)
{
s = s.substring(index+sub.length());
count++;
}
return count;
}
//获取字串个数,方法二
public static int getSubCount_2(String s,String sub)
{
int count = 0;
int index =0;
while((index=s.indexOf(sub,index))!=-1)
{
index = index + sub.length();
count++;
}
return count;
}
//获取最大子串
public static String getMaxSubString(String s1,String s2)
{
String max = "",min = "";
max = (s1.length()>s2.length())?s1:s2;
min = (max == s1)?s2:s1;
for(int x=0;x<min.length();x++)
{
for(int y=0,z=min.length()-x;z!=min.length()+1;y++,z++)
{
String tmp = min.substring(y,z);
//sop(tmp);
if(max.contains(tmp))
return tmp;
}
}
return "";
}
}
|
|