当前位置:网站首页>字符串的相关编程题
字符串的相关编程题
2022-07-06 18:09:00 【胡阳阳Y】
字符串出现的次数
字符串A,另一个字符串B,计算B字符串在A字符串中出现几次
例子 : dsabdnabdsnabeabiwpabekabd **ab**
- 实现过程
- 对字符串进行索引查找 indexOf
- 找到的字符串的索引记录,进行字符串的截取
- 直到找打到未知, indexOf方法是-1
- 一旦找到了,计数器++
/**
* @param str 原始字符串
* @param sub 要查找的字符串
* @return 出现次数
*/
public static int stringCount(String str ,String sub){
//定义变量,计数器
int count = 0;
//定义变量,记录字符串查找后的索引
int index = 0;
//对字符串出现的位置,进行查询
//反复查找,使用循环while
//循环条件就是indexOf方法返回-1
while ( (index=str.indexOf(sub)) != -1 ) {
//执行了循环index !=-1 字符串出现了
count ++;
//截取字符串,开始索引 index+被查找字符串的长度
str = str.substring(index + sub.length());
}
return count;
}
哪个字符出现的最多
要求 : 指定字符串自能是(小写)字母 abeegewff , 计算出哪个字符出现的次数最多
限定字符串中字母只能有26个
> 找每个字符各自出现多少次,找出最大值
- 实现过程 :
- 字符串转成数组 (单个字符操作)
- 创建长度为26的数组,计数器使用
- 取出数组中的字符, (字符-97)对应数组的索引,计数器++
- 找出数组中的最大值
/**
* 查找字符串中,哪个字符出现的次数最多
* @param str 要查找字符串
* @return 返回出现次数最多的字符
*/
public static char charCount(String str){
//字符串转成数组
char[] chars = str.toCharArray();
//定义26长度的数组,保存每个字符出现的次数
int[] count = new int[26];
//遍历数组
for (int i = 0 ; i < chars.length; i++){
//取出单个字符
char ch = chars[i];
//字符 - 97 作为数组的索引使用 (数组,计数器数组)
count[ ch - 97 ] ++;
}
//System.out.println("Arrays.toString(count) = " + Arrays.toString(count));
//取出count数组中的,最大值的索引
int index = 0 ; //数组最大值索引
int max = count[0];
for(int i = 1 ; i < count.length ; i++){
if (max < count[i]){
index = i;
max = count[i];
}
}
//index索引,正好和字符相差97
return (char) (index+97);
}
边栏推荐
- Yunna | work order management measures, how to carry out work order management
- 公钥\私人 ssh避password登陆
- 鼠标右键 自定义
- Neon Optimization: summary of performance optimization experience
- AcWing 1142. 繁忙的都市 题解(最小生成树)
- go-zero微服务实战系列(九、极致优化秒杀性能)
- 今日问题-2022/7/4 lambda体中修改String引用类型变量
- Amway wave C2 tools
- table表格设置圆角
- docker 方法安装mysql
猜你喜欢
Body mass index program, entry to write dead applet project
Set WordPress pseudo static connection (no pagoda)
MySQL script batch queries all tables containing specified field types in the database
云呐-工单管理制度及流程,工单管理规范
Appium automation test foundation uiautomatorviewer positioning tool
Appium foundation - appium inspector positioning tool (I)
Appium基础 — Appium Inspector定位工具(一)
[advanced C language] 8 written questions of pointer
Send template message via wechat official account
2022 Google CTF SEGFAULT LABYRINTH wp
随机推荐
AcWing 361. 观光奶牛 题解(spfa求正环)
Body mass index program, entry to write dead applet project
AcWing 346. 走廊泼水节 题解(推公式、最小生成树)
Taro applet enables wxml code compression
Neon Optimization: an optimization case of log10 function
js如何快速创建一个长度为 n 的数组
【信号与系统】
dvajs的基础介绍及使用
黑马笔记---异常处理
2022 Google CTF SEGFAULT LABYRINTH wp
AcWing 344. 观光之旅题解(floyd求无向图的最小环问题)
域分析工具BloodHound的使用说明
mongodb查看表是否导入成功
Make Jar, Not War
盒子拉伸拉扯(左右模式)
Vocabulary in Data Book
AcWing 904. Wormhole solution (SPFA for negative rings)
设置Wordpress伪静态连接(无宝塔)
黑马笔记---创建不可变集合与Stream流
[advanced C language] 8 written questions of pointer