java實(shí)現(xiàn)統(tǒng)計(jì)字符串中字符及子字符串個數(shù)的方法示例
本文實(shí)例講述了java實(shí)現(xiàn)統(tǒng)計(jì)字符串中字符及子字符串個數(shù)的方法。分享給大家供大家參考,具體如下:
這里用java實(shí)現(xiàn)統(tǒng)計(jì)字符串中的字符(包括數(shù)字、大寫字母、小寫字母以及其他字符)個數(shù),以及字符串的子字符串的個數(shù)。
運(yùn)行效果圖如下:

具體代碼如下:
import java.util.Scanner;
public class Counter {
static Scanner scanner = new Scanner(System.in);
public static void count(String s) {
int low, upper, num, others;
low = upper = num = others = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.isDigit(s.charAt(i))) {
num++;
continue;
}
if (Character.isLowerCase(s.charAt(i))) {
low++;
continue;
}
if (Character.isUpperCase(s.charAt(i))) {
upper++;
continue;
} else {
others++;
}
}
System.out.println(" 大寫字母的個數(shù)為:" + upper + "\n 小寫字母的個數(shù)為:" + low+ "\n 數(shù)字的個數(shù)為: " + num + "\n 其他字符的個數(shù)為: " + others);
}
public static void subCounter(String str1, String str2) {
int counter = 0;
for (int i = 0; i <= str1.length() - str2.length(); i++) {
if (str1.substring(i, i + str2.length()).equalsIgnoreCase(str2)) {
counter++;
}
}
System.out.println("子字符串的個數(shù)為: " + counter);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("請輸入一個字符串:");
String string = scanner.nextLine();
count(string);
System.out.println("-----------------------------");
// 查詢在這個字符串中存在多少個子字符串str。
System.out.println("請輸入一個您想查詢的子字符串:");
String str = scanner.nextLine();
subCounter(string, str);
}
}
PS:這里再為大家推薦幾款在線字符統(tǒng)計(jì)工具供大家參考:
在線字?jǐn)?shù)統(tǒng)計(jì)工具:
http://tools.jb51.net/code/zishutongji
在線字符統(tǒng)計(jì)與編輯工具:
http://tools.jb51.net/code/char_tongji
希望本文所述對大家java程序設(shè)計(jì)有所幫助。
相關(guān)文章
SpringBoot用實(shí)體接收Get請求傳遞過來的多個參數(shù)的兩種方式
本文主要介紹SpringBoot用實(shí)體接收Get請求傳遞過來的多個參數(shù),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
springboot定時任務(wù)SchedulingConfigurer異步多線程實(shí)現(xiàn)方式
這篇文章主要介紹了springboot定時任務(wù)SchedulingConfigurer異步多線程實(shí)現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
springboot如何讀取application.yml文件
這篇文章主要介紹了springboot如何讀取application.yml文件的方法,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2020-12-12
解決SpringBoot application.yaml文件配置schema 無法執(zhí)行sql問題
這篇文章主要介紹了解決SpringBoot application.yaml文件配置schema 無法執(zhí)行sql問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
java.lang.UnsupportedOperationException分析及解決辦法
日常開發(fā)中我遇到j(luò)ava.lang.UnsupportedOperationException:異常兩次了,下面這篇文章主要給對大家介紹了關(guān)于java.lang.UnsupportedOperationException分析及解決辦法,需要的朋友可以參考下2024-03-03
SpringBoot統(tǒng)計(jì)、監(jiān)控SQL運(yùn)行情況的方法詳解
這篇文章主要給大家介紹了關(guān)于SpringBoot統(tǒng)計(jì)、監(jiān)控SQL運(yùn)行情況的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-02-02
Java多線程之Callable接口的實(shí)現(xiàn)
這篇文章主要介紹了Java多線程之Callable接口的實(shí)現(xiàn),Callable和Runnbale一樣代表著任務(wù),區(qū)別在于Callable有返回值并且可以拋出異常。感興趣的小伙伴們可以參考一下2018-08-08

