统计字符个数java
‘壹’ 编写java程序统计字符个数。
public static void main(String[] args) {
// TODO Auto-generated method stub
int abcCount=0;//英文字母个数
int spaceCount=0;//空格键个数
int numCount=0;//数字个数
int otherCount=0;//其他字符个数
Scanner scan=new Scanner(System.in);
String str=scan.nextLine();
char[] ch = str.toCharArray();
for(int i=0;i<ch.length;i++){
if(Character.isLetter(ch[i])){
//判断是否字母
abcCount++;
}
else if(Character.isDigit(ch[i])){
//判断是否数字
numCount++;
}
else if(Character.isSpaceChar(ch[i])){
//判断是否空格键
spaceCount++;
}
else{
//以上都不是则认为是其他字符
otherCount++;
}
}
System.out.println("字母个数:"+abcCount);
System.out.println("数字个数:"+numCount);
System.out.println("空格个数:"+spaceCount);
System.out.println("其他字符个数:"+otherCount);
‘贰’ java怎么实现统计一个字符串中字符出现的次数
可陵首迅以用String的indexof(str,fromindex)方法,循环遍历加一个计数器统计次数。
publicclassCountTimes{
publicstaticvoidmain(String[]args){
Stringstr="Intheentireworldthere'";
inttimes=searchstr("my",str);//返回2
System.out.println(times);
}
publicstaticintsearchstr(Stringkey,Stringstr){
int尺此index=0;//每次的搜索到的下标
intcount=0;//计数器
while((index=str.indexOf(key,芹启index))!=-1){
index=index+key.length();
count++;
}
returncount;
}
}
‘叁’ 鐢╦ava 缂栧啓涓涓绋嫔簭锛屾帴鍙楃敤鎴疯緭鍏ョ殑涓娈佃嫳鏂囨枃瀛楋纴缁熻″嚭鍏朵腑镄勫瓧绗︿釜鏁般佸崟璇崭釜鏁板拰鍙ュ瓙镄勪釜鏁般
public static void main(String[] args)
{
System.out.println("璇疯緭鍏ヨ嫳璇鐗囨,浠';'缁撴潫:");
Scannerscanner = newScanner(System.in);
String str = "";
int dc = 0;
int zc = 0;
intjc= 0;
while(scanner.hasNext())
{
str = scanner.next();
zc += str.length();
dc++;
System.out.println(str);
if (str.contains("."))
{
jc+= 1;
}
if (str.contains(";"))
{
break;
}
}
// scanner.
System.out.println("鍗曡瘝涓鏁颁负:" + dc);
System.out.println("瀛楁瘝鏁颁负锛" + (zc - 1));
System.out.println("鍙ユ暟涓:" +jc);
}
镓╁𪾢璧勬枡锛
import java.io.*;
public class test
{ public static void main(String[] args) throws IOException
{ System.out.print("璇疯緭鍏ヤ竴涓插瓧姣:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in))锛
String str=br.readLine();
int char1=0,letter=0,sentence=0;
for(int i=0;i<str.length();i++)
{
char ch = str.charAt(i);
if(ch!=' ')
{ char1++;
}
if(ch==' '||ch=='/n')
{ //链夌┖镙,锷犱竴鍗曡瘝
if(i!=0&&str.charAt(i-1)!=' ')
letter++;
}
if(ch=='?'||ch=='!'||ch=='.')
{ sentence++;
}
}
System.out.println("瀛楃︽暟锛"+char1);
System.out.println("鍗曡瘝涓鏁:"+letter);
System.out.println("鍙ュ瓙鏁:"+sentence)锛
}
}
import java.io.*;
public class test
{ public static void main(String[] args) throws IOException
{ System.out.print("璇疯緭鍏ヤ竴涓插瓧姣:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
int char1=0,letter=0,sentence=0;
for(int i=0;i<str.length();i++)
{
char ch = str.charAt(i);
if(ch!=' ')
{ char1++;
}
if(ch==' '||ch=='/n')
{ //链夌┖镙,锷犱竴鍗曡瘝
if(i!=0&&str.charAt(i-1)!=' ')
letter++;
}
if(ch=='?'||ch=='!'||ch=='.')
{ sentence++;
}
锝
System.out.println("瀛楃︽暟锛"+char1);
System.out.println("鍗曡瘝涓鏁:"+letter);
System.out.println("鍙ュ瓙鏁:"+sentence);
}
}