本文實例講述了java實現統計字符串中字符及子字符串個數的方法。分享給大家供大家參考,具體如下:
這裡用java實現統計字符串中的字符(包括數字、大寫字母、小寫字母以及其他字符)個數,以及字符串的子字符串的個數。
運行效果圖如下:
具體代碼如下:
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(" 大寫字母的個數為:" + upper + "/n 小寫字母的個數為:" + low+ "/n 數字的個數為: " + num + "/n 其他字符的個數為: " + 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("子字符串的個數為: " + 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:這裡再為大家推薦幾款在線字符統計工具供大家參考:
在線字數統計工具:
http://tools.VeVB.COm/code/zishutongji
在線字符統計與編輯工具:
http://tools.VeVB.COm/code/char_tongji
希望本文所述對大家java程序設計有所幫助。