public class StringTest_1
{
//对字符串数组进行排序
public static void stringSort(String[] arr)
{
//采用冒泡排序
for(int i=0;i<arr.length-1;i++)
{
for(int j=0;j<arr.length-1-i;j++)
{
//用compareTo方法进行字符串比较
if(arr[j].compareTo(arr[j+1])>0)
{
String temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
showArray(arr);
}
//定义方法,以[str1,str2,str3]的格式来打印数组
public static void showArray(String[] arr)
{
System.out.print("[");
for(int i=0;i<arr.length;i++)
{
if(i!=arr.length-1)
System.out.print(arr[i]+",");
else
{
System.out.print(arr[i]+"]\n");
}
}
}
public static void main(String[] args)
{
String arr[]={"nba","abc","cba","zz","qq","haha"};
//打印数组
showArray(arr);
//对数组进行排序并输出
stringSort(arr);
}
}
public class StringTest_2
{
public static void main(String[] args)
{
String str="abcqwabcedcxabcuabcjkabcnmbabc";
//String str=null;
try
{
int count=countChildStr(str,"abc");
System.out.println("abc在"+str+"中出现的次数为:"+count);
}
catch (NullPointerException ne)
{
System.out.println(ne);
}
catch(RuntimeException re)
{
System.out.println(re);
}
}
public static int countChildStr(String str,String key)
{
if(str==null||key==null)
{
throw new NullPointerException("空指针异常,源字符串和子串都不能为NULL");
}
if(key=="")
{throw new RuntimeException("调用不合法,子串要有内容");}
int count=0,index=0;
while((index=str.indexOf(key,index))!=-1)
{
count++;
index+=key.length();
}
return count;
}
}
public class StringTest_3
{
public static void main(String[] args)
{
//创建两个不为空的字符串
String str1="abxczwsxcvdfas";
//String str1=null;
String str2="ghwsxcvxcdbgthnnnrfqwe";
try
{
String str=searchMaxCommonStr(str1,str2);
System.out.println("最大公共子串是:"+str);
}
catch (NullPointerException ne)
{
System.out.println(ne);
}
}
public static String searchMaxCommonStr(String str1,String str2)
{
if(str1==null||str2==null)
throw new NullPointerException("空指针异常,参数不能为Null");
//断定较长字符串和较短字符串
String max=(str1.length()>str2.length())?str1:str2;
String min=(str1.equals(max))?str2:str1;
//按长度递减的方式取子串,从min.length~~1
for(int i=min.length();i>0;i--)
{
for(int x=0,y=x+i;y<min.length();x++,y++)
{
String childStr=min.substring(x,y);
//若较长字符串中包含此子串,则找到了
//否则继续找
if(max.contains(childStr))
return childStr;
}
}
return null;
}
}
public class StringTest_4
{
public static void main(String[] args)
{
String str=" abc ws ";
str=myTrim(str);
System.out.println(str);
}
public static String myTrim(String s)
{
int begin=0,end=s.length()-1;
//从头遍历
while(begin<=end && s.charAt(begin)==' ')
{
begin++;
}
//从尾部遍历
while(begin<=end && s.charAt(end)==' ')
{
end--;
}
return s.substring(begin,end+1);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有