栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java:获取匹配项在字符串中的位置的方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java:获取匹配项在字符串中的位置的方法?

执行此操作的方法家族是:

  • int indexOf(String str)
  • indexOf(String str, int fromIndex)
  • int lastIndexOf(String str)
  • lastIndexOf(String str, int fromIndex)

返回指定子字符串的第一个(或最后一个)出现在此字符串内的索引[ 从指定索引处开始向前(或向后搜索)]。

String text = "0123hello9012hello8901hello7890";String word = "hello";System.out.println(text.indexOf(word)); // prints "4"System.out.println(text.lastIndexOf(word)); // prints "22"// find all occurrences forwardfor (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {    System.out.println(i);} // prints "4", "13", "22"// find all occurrences backwardfor (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {    System.out.println(i);} // prints "22", "13", "4"


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517713.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号