String生成缩略词的工具类

String生成缩略词的工具类

1.类的功能

编写一个生成缩略词的工具类

 要求:用各个单词的首字母大写,如果单词是the of and 就忽略如

the class of java and jsp 应变为 CJJ

2.Abbreviation(缩略词工具类)

public class Abbreviation {  
    //去指定单词  
    public String[] RemoveWord(String s){  
        //先转化为字符串数组,方便后面使用for语句  
        String[] aa=s.split(" ");  
        //循环字符串数组将指定的字符替换成空格  
        for(int i=0;i<aa.length;i++){  
            if((aa[i].equals("the"))||(aa[i].equals("of"))||(aa[i].equals("and"))){  
                aa[i]=" ";  
            }  
        }  
  //返回新的字符串数组  
        return aa;  
    }  
    //将字符串数组中的每个元素的第一个字母以大写的形式取出来  
    public String[] Initials(String[] a){  
        //给要存放的(要返回的)字符串开辟空间(注意:数组长度不能‘=’以免数组越界)  
        String[] str=new String[a.length];  
        for(int i=0;i<a.length;i++){  

//String.value():将char类型转换为String,toUpperCase():转换为大写,charAt(0):取字符串中的第一个字符
  
            str[i] =String.valueOf(a[i].toUpperCase().charAt(0));  
        }  
        return str;  
    }  
  
} 


3.AbbreviationTest(测试类)
public class AbbreviationTest {  
  
    public static void main(String[] args){  
          
        System.out.println("Please output into the String!");  
        //从键盘输入字符  
        Scanner sc = new Scanner(System.in);  
        //获取输入的字符串  
        String s=sc.nextLine();  
          
        //创建对象(用来调用方法)  
        Abbreviation p = new Abbreviation();  
        //先除去指定字符  
        String[] pp=p.RemoveWord(s);  
        //完成相应功能  
        String[] e=p.Initials(pp);  
          
//StringBUffer类实现将字符串数组转换为字符串  
        StringBuffer sb = new StringBuffer();  
        for(int i = 0; i < e.length; i++)  
        {   
           sb. append(e[i]);  
        }  
        String s1 = sb.toString();  

//用replaceAll方法将字符串总的空格替换没了  

        System.out.println(s1.replaceAll(" ", ""));  
    }  
}  



4.笔记

split(参数):字符串->数组(参数为分割符号)


       注意:
            A:这里参数是正则表达式
   B:可能加多个反斜杠
            C:竖杠有特殊含义(竖线‘或’的意思)\\d(按照数字去分割)
            D:‘.’任意字符




toCharArry():输出数组






 ==:同一个(对象)  equals:内容(值)相同
     字符串池
     intern():去字符串池中取找


   异常


try ...catch 


catch中不要空着


  A:catch捕捉最近的try抛出的异常
  B:当异常被捕捉后不能再被别的catch语句捕捉


RuntimeException(运行时异常) 


Throwable类方法
getMessage()
A:取得异常对象的信息描述  
        B:从抛出的异常中的参数中获得信息


 JDK7以上catch中‘|’分隔符捕获多个异常

猜你喜欢

转载自blog.csdn.net/fyangfei/article/details/78704420