首页 > Java > 正文

在 String Java 中查找给定单词后的特定单词索引

WBOY
发布: 2024-02-22 13:40:07
转载
1026 人浏览过

在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):

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中文网其他相关文章!

相关标签:
来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!