當前位置:首頁 » 編程語言 » java字元串統計

java字元串統計

發布時間: 2023-05-20 04:44:40

1. java統計串中字元個數的代碼解釋

整個代碼就是為了統計字元串中各個字元出現的個數
Map
result
=
getCharMaps(s);
這個方法調用
主要是看這個方法
public
static
Map
getCharMaps(String
s)
{
Map
map
=
new
HashMap();
//定義一個map
for(int
i
=
0;
i
<
s.length();
i++)
{
//
下面的代碼主要是循環字元串,一次取出每一個字元
Character
c
=
s.charAt(i);
//獲取對應的字元
Integer
count
=
map.get(c);
//獲取字元對應出現的次數
map.put(c,
count
==
null
?
1
:
count
+
1);
//如果之前出現過,則加1,否則直接賦1
}
return
map;
//返回最終的map
}

2. 編寫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);

3. java怎麼實現統計一個字元串中字元出現的次數

這是我剛根據你的需求寫的,你可以參考一下!

我辦法很簡單,拆分存放數組裡面,然後查找數組就可以了!
其實還有更簡單的辦法,直接用容器比較方便,目前這個辦法我自己用數組寫的,我個人挺滿意的!
importjava.util.Scanner;
publicclass統計次數
{
privatestaticScannersc=newScanner(System.in);
publicstaticvoidmain(String[]args)
{
System.out.println(" ==========統計字元串中字元次數========== ");
init();
}//初始化!
privatestaticvoidinit()
{
for(;;)
{
System.out.println("輸入文字:");
char[]arr1=fenJie(input());
System.out.println("查找的字:");
charx=muBiao(fenJie(input()));
inty=chaZhao(arr1,x);
System.out.println("你要找的是""+x+"",出現"+y+"次 =============== ");
}
}
//錄入!
privatestaticStringinput()
{
Strings=sc.next();
returns;
}
//分解!
privatestaticchar[]fenJie(Strings)
{
char[]arr=newchar[s.length()];
for(inti=0;i<s.length();i++)
{
arr[i]=(char)(s.charAt(i));
}
returnarr;
}
//查找!
privatestaticintchaZhao(char[]arr,charx)
{
intnum=0,tem=-1;
for(inta=0,b=arr.length-1;a<=b;a++,b--)
{
if(a!=b&&arr[a]==x)num++;
if(a!=b&&arr[b]==x)num++;
if((a==b)&&(arr[a]==x||arr[b]==x))num++;
tem=num;
}
returntem;
}
//目標
privatestaticcharmuBiao(char[]arr)
{
returnarr[0];
}
}

4. java中如何統計某個字母在一個字元串中出現了多少次啊

1、根據length獲取字元串長度

Strings="abcdedfae";//定義一個斗友字元串知滲
intlen=s.length();//獲取原來的字元串長度

2、通過replaceAll方式,把搭銷脊字元串中該字母替換成空

Strings1=s.replaceAll(要統計的字母,"");

3、獲取替換後的字元串長度

intlen2=s1.length();

4、原來的字元串長度減去替換後的字元串長度就是該字母出現的次數

intlenTimes=len1-len2;//出現的次數
熱點內容
linux應用程序開發pdf 發布:2025-07-15 10:11:37 瀏覽:910
解壓冷知識 發布:2025-07-15 10:11:35 瀏覽:78
outlook郵件的伺服器是什麼 發布:2025-07-15 09:45:59 瀏覽:482
如何安排資產配置 發布:2025-07-15 09:33:24 瀏覽:906
更新傳送伺服器目的地址失敗 發布:2025-07-15 09:27:05 瀏覽:484
c語言else的用法 發布:2025-07-15 09:19:54 瀏覽:119
tnt蘋果核安卓怎麼加好友 發布:2025-07-15 09:05:15 瀏覽:239
年輕人運行內存為什麼比安卓好 發布:2025-07-15 08:52:03 瀏覽:515
怎麼配置組策略 發布:2025-07-15 08:52:02 瀏覽:246
pythonjson格式 發布:2025-07-15 08:42:54 瀏覽:678