在java编程中,查找给定单词后的特定单词索引是一个常见问题。在string类中,有多种方法可以实现这一功能。本文将通过具体案例演示如何在java中使用这些方法来查找目标单词并获取其索引位置。让我们一起跟随php小编苹果的指导,深入了解这一有用的技巧。
假设我有字符串
String str = "Hello all, the world is going to end here and I am the only end character which is in the end game of the end world";
现在我想编写一个函数,在其中传递整个字符串、matchingword、wordtofindaftermatchingword
所以假设我想找到“game”的索引,但是“game”单词应该在“end”单词之后,并且“end”单词可以在 string 中出现 n 次。我不想使用正则表达式,因为我正在考虑使这个函数通用。
正如有人所说,您可以使用带有起始索引的方法indexof(string,int):
立即学习“Java免费学习笔记(深入)”;
public static int indexof(string str, string word, string precededby) {
int i = str.indexof(precededby);
if (i < 0) {
return -1;
}
return str.indexof(word, i+precededby.length());
}现在这个:
System.out.println(indexOf(str, "game", "end"));
将打印 94
以上就是在 String Java 中查找给定单词后的特定单词索引的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号