java实现统计字符串中字符及子字符串个数的方法示例
作者:aitaoke 时间:2022-10-14 13:47:40
本文实例讲述了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.jb51.net/code/zishutongji
在线字符统计与编辑工具:
http://tools.jb51.net/code/char_tongji
希望本文所述对大家java程序设计有所帮助。
标签:java,统计,字符串,字符
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Springmvc Controller接口代码示例
2023-11-28 10:13:25
Android的异步任务AsyncTask详解
2021-10-13 02:58:28
详解Kotlin中的面向对象(二)
2021-12-29 03:10:00
C# Websocket连接实现wss协议
2022-09-02 08:20:41
C#比较时间大小的方法总结
2023-09-02 04:38:06
![](https://img.aspxhome.com/file/2023/1/122701_0s.jpg)
SpringBoot的@Value给静态变量注入application.properties属性值
2023-09-20 11:54:07
C/C++与Java各数据类型所占字节数的详细比较
2022-09-08 11:39:55
SpringMVC Json自定义序列化和反序列化的操作方法
2022-11-15 13:07:49
Android小程序实现选项菜单
2022-04-12 00:34:01
![](https://img.aspxhome.com/file/2023/5/114285_0s.jpg)
android自由改变Dialog窗口位置的方法
2021-09-13 04:19:04
Android开发教程之如何屏蔽View的重复点击
2021-05-27 10:06:56
C#实现Dictionary字典赋值的方法
2021-12-09 17:55:40
![](https://img.aspxhome.com/file/2023/3/122693_0s.png)
C#实现数字华容道游戏
2023-10-26 10:01:07
![](https://img.aspxhome.com/file/2023/2/94542_0s.jpg)
Java面向对象程序设计:类的定义,静态变量,成员变量,构造函数,封装与私有,this概念与用法详解
2022-07-12 03:35:14
![](https://img.aspxhome.com/file/2023/5/61885_0s.png)
Java @Accessors注解图文详解
2023-10-10 06:06:51
![](https://img.aspxhome.com/file/2023/2/73072_0s.png)
Java字符串split使用方法代码实例
2023-02-06 18:55:31
![](https://img.aspxhome.com/file/2023/2/68002_0s.png)
Java中的zookeeper常用命令详解
2022-12-07 05:46:35
![](https://img.aspxhome.com/file/2023/2/62752_0s.png)
springboot大文件上传、分片上传、断点续传、秒传的实现
2023-06-16 02:18:30
Android编程之菜单实现方法
2023-12-21 16:41:24
![](https://img.aspxhome.com/file/2023/8/111668_0s.png)
Java的接口和抽象类深入理解
2023-01-26 02:19:22