当前位置:网站首页>字符串的相关编程题
字符串的相关编程题
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);
}
边栏推荐
猜你喜欢

【C语言进阶篇】指针的8道笔试题

Yunna - work order management system and process, work order management specification

AcWing 1148. 秘密的牛奶运输 题解(最小生成树)

字节P7专业级讲解:接口测试常用工具及测试方法,福利文

Send template message via wechat official account

云呐|工单管理办法,如何开展工单管理

Make Jar, Not War

MySQL script batch queries all tables containing specified field types in the database

405 method not allowed appears when the third party jumps to the website

修改px4飞控的系统时间
随机推荐
机器学习:随机梯度下降(SGD)与梯度下降(GD)的区别与代码实现。
Byte P7 professional level explanation: common tools and test methods for interface testing, Freeman
Go zero micro service practical series (IX. ultimate optimization of seckill performance)
【C语言进阶篇】指针的8道笔试题
c语言—数组
405 method not allowed appears when the third party jumps to the website
DS-5/RVDS4.0变量初始化错误
ClickHouse字段分组聚合、按照任意时间段粒度查询SQL
C language - array
Google发布安全更新,修复Chrome中已被利用的0 day
The difference between Tansig and logsig. Why does BP like to use Tansig
C language instance_ three
736. LISP syntax parsing: DFS simulation questions
Dark horse notes - exception handling
Machine learning: the difference between random gradient descent (SGD) and gradient descent (GD) and code implementation.
新工作感悟~辞旧迎新~
Taro2.* applet configuration sharing wechat circle of friends
C语言实例_4
2022 Google CTF SEGFAULT LABYRINTH wp
Spark TPCDS Data Gen