java从循环LinkedList中的字符串中查找给定单词的起始索引
我试图用java生成一个程序,它将字符串输入和第二个输入作为一个单词,我试图从给定的字符串中找到该单词的起始索引。如果单词不止一次出现,它应该给出所有的起始索引
输入字符串:
ped come wrapped to wrap
输入单词(需要找到起始索引):
包裹
渴望输出:
9 20
我制作了一个程序,可以找到给定单词的起始索引。然而,我正在努力添加一个逻辑,比如,如果您看到我的输入字符串(last_word+first_word)=wrapped
(我正在寻找的一个单词),那么我也需要在输出中获得最后一个单词的起始索引
这就是我到目前为止所产生的结果
public class Practice {
public static void findWordIndex(String text, String word) {
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; ) {
System.out.println(i);
}
}
public static void main(String[] args){
Practice p = new Practice();
p.findWordIndex("ped come wrapped the wrap", "wrapped");
}
}
# 1 楼答案
到目前为止,你有一个良好的开端
这将解决您的问题:
我希望这有帮助。如果没有,请告诉我!此外,执行此操作时:
您不必创建当前正在使用的类的实例。您应该能够直接调用findWordIndex:
# 2 楼答案
以牺牲空格为代价,我找到了一种根据您的问题获取字符串索引的方法,在这个解决方案中,我没有使用
IndexOf()
,我所做的是,我使用了两个Arraylist
,一个用于单词(空格为ommited),另一个用于每个字符串的长度,我使用迭代来获取这些字符串的索引,并检查两个单词的组合equal
是否为指定的word
。在匹配空格后,我的输出是[7,16]。这是我的密码: