题解 | #统计字符串中字母出现次数#

统计字符串中字母出现次数

http://www.nowcoder.com/practice/83350872bdb5406fa706895d5efb1c55


public class Main {
    public static void main(String[] args) {
        String string = "H e l l o ! n o w c o d e r";
        Scanner scanner= new Scanner(System.in);
        String word = scanner.next();
        scanner.close();
        System.out.println(check(string, word));
    }

    public static int check(String str, String word) {

        //write your code here......
         char c = word.charAt(0); //将第二个字符串用字符表示
        int count = 0;
        for(int i = 0; i < str.length(); i++) //遍历第一个字符串
            if(c == str.charAt(i)) //比较每个字符与c是否相同
                count++; //相同则计数
        return count;
    }
}

也有另一种方法:

        return str.length() - str.replace(word,"").length();
    }

replace() 方法通过用 newChar 字符替换字符串中出现的所有 searchChar 字符,并返回替换后的新字符串。即将word字符直接消去。用原字符长度-消去后长度=word出现次数。

全部评论

相关推荐

独特的菜鸡想要off...:今天被同一个hr捞了,姐姐你招我进去的你不记得吗
点赞 评论 收藏
分享
也许是天气_:实习这块全是假大空像AI生成的,没有实际内容。要体现出难点、亮点、解决问题的过程
点赞 评论 收藏
分享
09-28 18:14
门头沟学院 Java
小肥罗:离谱,那我的简历可以这么写:颜值高大长腿,一张臭嘴不要脸,四只眼瓜子脸,入职不用买保险。
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务