gpt4 book ai didi

java - 查找字符串 2 在字符串 1 中开始的索引

转载 作者:行者123 更新时间:2023-12-01 12:20:21 28 4
gpt4 key购买 nike

所以我正在编写一个具有多种不同方法的程序,其中一个方法要求查找第二个字符串在第一个字符串中开始的索引

该方法接受两个字符串作为参数,并返回第二个字符串在第一个字符串中开始的位置的字符索引。例如:

IN:乐高积木,出发

输出:2

此方法的要点是我只能使用 String 中的 charAtsubstringlength类,并且没有其他类方法

我目前没有代码,我需要了解如何启动它

编辑:感谢您的帮助,现在我不想查找第二个字符串开始的索引,而是想找到第二个字符串在第一个字符串的最右侧区域开始的索引。例如

IN:密西西比州,SS输出:5

提前致谢

最佳答案

public int indexOf(final String source, final String find) {
// loop from first character to last character that still leaves length of 'find' string available
for(int sourcePos = 0; sourcePos < source.length() - find.length(); sourcePos++) {
boolean found = true;
for(int findPos = 0; findPos < find.length(); findPos++) {
// if the current char is not a match, then mark as not found and break from loop
if(source.charAt(sourcePos) != find.charAt(findPos)) {
found = false;
break;
}
}
if(found) {
return sourcePos;
}
}

// return -1 to indicate the string was not found
return -1;
}

关于java - 查找字符串 2 在字符串 1 中开始的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26708394/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com