(一)题目描述
编写一个函数,计算字符串中含有的不同字符的个数。字符在ACSII码范围内(0~127)。不在范围内的不作统计。
输入描述:
输入N个字符,字符在ACSII码范围内。
输出描述:
输出范围在(0~127)字符的个数。
示例1
输入
abc
输出
3
(二)解答
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.next();
char[] buf = str.toCharArray();
//此处要注意将字符串转化为字符数组的方式,可以总结一下
HashSet<Character> hs = new HashSet<>();
//题目要求的是传进的字符串中不同字符的个数
for(int i=0;i<buf.length;i++){
hs.add(buf[i]);
}
int count = 0;
for(char s:hs){
//求字符的ASCII码
//if(Integer.valueOf(s)>0 && Integer.valueOf(s)<127){
if((int)s>0 && (int)s<127){
count++;
//System.out.print(s);
}
}
System.out.println(count);
}
}
扫描二维码关注公众号,回复:
2299275 查看本文章
(三)总结:总结一下将字符串转化为数组的方法
(1)由char型字符组成的字符串转化为数组:使用toCharArray()方法
package cn.niu.xiti;
public class Test1 {
public static void main(String[] args) {
String str = "jaybillions";
char[] buf = str.toCharArray();
for(Character s:buf){
System.out.print(s+" ");
}
}
}
console:j a y b i l l i o n s
(2)使用String的charAt()方法获取每一个位置的字符,将其放入一个新的数组中存储
package cn.niu.xiti;
public class Test1 {
public static void main(String[] args) {
String str = "19930415";
char[] buf = new char[str.length()];
for(int i=0;i<buf.length;i++){
buf[i] = str.charAt(i);
}
for(Character num:buf){
System.out.print(num+" ");
}
}
}
console:1 9 9 3 0 4 1 5
(3)String的字符串截取方法substring(a,b);包含头部不包含尾部
package cn.niu.xiti;
public class Test1 {
public static void main(String[] args) {
String str = "Stephen chow";
String[] buf = new String[str.length()];
for(int i=0;i<buf.length;i++){
buf[i] = str.substring(i,i+1);
}
for(String num:buf){
System.out.print(num+" ");
}
}
}
console:S t e p h e n c h o w