栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

import java.util.Scanner;

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......
    }
}

解法一

str.length() 用来获取字符串中字符的个数,包括空格符。
str.replace(word, “”) 的作用是将字符串中指定字符移除。
str.replace(word, “”).length() 是移除指定字符后的字符串长度。
所以 str.length() - str.replace(word, “”).length() 就是原字符串中指定字符的个数。

public static int check(String str, String word) {
    //write your code here......
    return str.length() - str.replace(word, "").length();
}

解法二

遍历字符串,将输入的字符和字符串的每个字符进行比较,如果相同,则count++

str.charAt() 用于返回字符串中指定索引处的字符。
由于输入的字符用 String 类型保存而不是 Char 类型,所以需要用 word.charAt(0) 获取该字符 (charAt() 得到的是字符类型)。

private static int check2(String str, String word) {
   //write your code here......
   int count = 0;
   for (int i = 0; i < str.length(); i++) {
       if(str.charAt(i) == word.charAt(0)){
           count++;
       }
   }
   return count;
}

解法三

遍历字符串,将每个字符转成 String 类型,然后通过 equals 和 输入的字符 (题目中输入的字符使用 String 来保存) 进行比较,一样则count++

public static int check(String str, String word) {
    //write your code here......
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if(word.equals(str.charAt(i)+"")){
            count++;
        }
    }
    return count;
}

解法四 (不推荐)

将字符串中的每个字符保存 ArrayList 集合中,然后通过 Collections 类的 frequency 方法来获取指定元素的个数. ( frequency(Collection c, Object o)主要用来获取指定集合中指定元素的个数 )

public static int check(String str, String word) {
    //write your code here......
    ArrayList list = new ArrayList();
    for (int i = 0; i < str.length(); i++) {
        list.add(str.charAt(i));
    }
    return Collections.frequency(list, word.charAt(0));
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/716275.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号