手写实现indexOf
2024-10-07 16:23:13
突然奇想。自己手写一个indexOf
package com.toov5.test; public class Test8 { public static int find(String str1, String str2) { char[] str1Arr = str1.toCharArray();
char[] str2Arr = str2.toCharArray(); int str1Length = str1.length();
int str2Length = str2.length(); int str1Index = 0;
int str2Index = 0; while ( (str1Index < str1Length) && (str2Index < str2Length)) {
if (str1Arr[str1Index] == str2Arr[str2Index]) {
str1Index++;
str2Index++;
}else {
str1Index = str1Index -str2Index +1;
str2Index = 0;
} } int index = str2Length == str2Length ? (str2Length > 1 ? str1Index - str2Index : str2Index -1 ) : -1;
return index; } }
易读性的,练练代码能力:
package com.toov5.test; public class TestOk1 { public static int getIndex(String str1 ,String str2) { String LonggerStr = str1.length() > str2.length() ? str1 : str2;
String ShorterStr = str1.length() > str2.length() ? str2 : str1;
int mark = 0; //标记位置 for(int i=0 ; i< LonggerStr.length(); i++) {
if (LonggerStr.charAt(i) == ShorterStr.charAt(0)) {
mark = i;
int index = i;
int shortIndex = 0;
while (LonggerStr.charAt(index++) == ShorterStr.charAt(shortIndex++) && shortIndex < ShorterStr.length());
if (shortIndex<ShorterStr.length()-1) {
mark=-1;
}
return mark;
} } return mark; } public static void main(String[] args) {
String str1 ="rewrf3eucksfddw";
String str2 = "fuck"; int result = getIndex(str1, str2);
System.out.println(result); } }
最新文章
- Java基础知识
- django 数据库交互
- (转载)C++创建对象的两种方法
- POJ 2502 Subway(迪杰斯特拉)
- TinyXML用法小结
- 五十个小技巧提高PHP执行效率(二)
- 使用NPOI导入导出标准Excel
- 029 Es面试小节
- caffe 根据txt生成多标签LMDB数据
- 基于vue与vux做的可滑动tab组件(附源码)
- Python全栈学习_day004作业
- PHP 获取上月,本月,近15天,近30天日期
- 本地开启apache虚拟服务器
- 去掉UITableView多余的分割线
- SpringBoot(八)_springboot集成swagger2
- bzoj3173
- jQuery实现简单前端搜索功能
- bzoj 1857
- 26_java之进程|线程|线程池
- mysql查询结果带上序号