编写一个字符串功能类StringFunctuin

时间:2022-3-5    作者:老大夫    分类: Java作业


编程题
1.编写一个字符串功能类StringFunctuin 有如下方法:
(1)方法1:public int getWordNumber(String s) throws Exception
参数是一个英文句子,方法的功能是取得此英文句子的单词个数。如果参数为空或为空字符串,抛出异常,异常信息为:”字符串为空”。
(2)方法2:public int getWordNumber(String s1,String s2) throws Exception 此方法传递2个String参数,返回s1中出现s2的次数。
(3)方法3:public boolean contain(String s1, String s2) throws Exception 判断S1中是否含有S2
编写测试主类Test, 对此类进行测试。

public class StringFunctuin {
    //检查字符串含有多少个字母
    public int getWordNumber(String s) throws Exception{
        int count=0;
        if(s==null||s.length()<=0){
            throw new NullPointerException("字符串为空!");
        }
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            if((c>='A'&&c<='Z')||(c>='a'&&c<='z')){
                    count++;
            }
        }
        return count;
    }
    //判断s1 里有 几个 s2    (我写反了,就当是s2是s1吧)
    public int getWordNumber(String s2,String s1) throws Exception {
        //检查字符串是否为空
        if(s1==null||s2==null){
            return 0;
        }
        if(s1.length()<=0||s2.length()<=0){
            return 0;
        }
        //s1 和 s2 分别存入 c1  c2字符数组
        char[] c1=new char[s1.length()];
        for(int i=0;i<s1.length();i++){
            c1[i]=s1.charAt(i);
        }
        char[] c2=new char[s2.length()];
        for(int i=0;i<s2.length();i++){
            c2[i]=s2.charAt(i);
        }
        //设置标志变量  flag
        int flag=0;
        // 设置计数变量 count
        int count=0;
        //遍历大字符串
        for(int i=0;i<s2.length();i++){
            //当检查到小字符串的首字母时
            if(c2[i]==c1[0]){
                //开始从 第i个位置遍历 s2 中是否有一段 s1
                for(int j=0;j<s1.length();j++){
                    //如果其中的每个字符都相同,标志变量会保持为 1
                    if(c2[i+j]==c1[j]){
                        flag=1;
                    }else{  //如果有哪个字符不符合s1  那么标志变量会变为0
                        flag=0;
                    }
                }
                //标志变量为1 表示上方小段遍历成功匹配一段,计数变量+1
                if(flag==1){
                    count++;
                    flag=0;
                }
            }
        }
        //返回成功匹配的段数
        return count;
    }
    //判断 s1中 是否含有 s2,  s1是大串   s2是小串
    public boolean contain(String s1,String s2)throws Exception{
        return getWordNumber(s1,s2)>0;
    }
}

版权所有:伸手党盘
文章标题:编写一个字符串功能类StringFunctuin
文章链接:https://ssdpan.cn/?post=14
本站文章来源于网络搜集和原创,仅供学习使用,未经授权请勿用于任何商业用途,如有侵权及时联系删除

推荐阅读:


扫描二维码,在手机上阅读