本文共 1068 字,大约阅读时间需要 3 分钟。
编写一个函数,计算字符串中含有的不同字符的个数。字符在ASCII码范围内(0~127),换行表示结束符,不算在字符里。不在范围内的字符不作统计。多个相同的字符只计算一次。
输入N个字符,字符在ASCII码范围内。
输出范围在(0~127)字符的个数。
输入:abc输出:3
思路:
实现:
import java.util.HashSet;import java.util.Set;public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { String str = input.nextLine(); System.out.println(countChar(str)); } } public static int countChar(String str) { Set set = new HashSet<>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= 0 && c <= 127) { if (!set.contains(c)) { set.add(c); } } } return set.size(); }} 注意:以上代码使用HashSet来存储字符,确保每个字符只存储一次。countChar函数遍历字符串的每个字符,检查字符是否在ASCII范围内,并且是否已经存在于集合中。如果满足条件,则将字符添加到集合中。最后,集合的大小即为不同字符的个数。
转载地址:http://wpjwz.baihongyu.com/