【发布时间】:2015-12-23 15:41:24
【问题描述】:
我正在尝试在 Java 中查找字符串中所有出现的子字符串。
例如: 为“asdf”搜索“ababsdfasdfhelloasdf”将返回 [8,17],因为有 2 个“asdf”,一个在位置 8,一个在 17。 在“aaaaaa”中搜索“aa”将返回 [0,1,2,3,4],因为在 0、1、2、3 和 4 位置有一个“aa”。
我试过了:
public List<Integer> findSubstrings(String inwords, String inword) {
String copyOfWords = inwords;
List<Integer> indicesOfWord = new ArrayList<Integer>();
int currentStartIndex = niwords.indexOf(inword);
int indexat = 0;
System.out.println(currentStartIndex);
while (cthing1 > 0) {
indicesOfWord.add(currentStartIndex+indexat);
System.out.println(currentStartIndex);
System.out.println(indicesOfWord);
indexat += cthing1;
copyOfWords = copyOfWords.substring(cthing1);
System.out.println(copyOfWords);
cthing1 = copyOfWords.indexOf(inword);
}
这个问题可以用 Python 解决如下:
indices = [m.start() for m in re.finditer(word, a.lower())]
其中“word”是我要查找的单词,“a”是我要搜索的字符串。
如何在 Java 中实现这一点?
【问题讨论】:
-
我觉得顶帖here可能对你有帮助。要获取索引,只需在收到时打印或保存
lastIndex。 -
你的意思是你需要something like this?
-
请使用更有意义的变量名。很难理解
cthing1或outthing或niwords是什么意思。使用lastIndex、indexList之类的东西会更容易理解你写的内容并更正它。
标签: java regex string substring