【问题标题】:Find all occurrences of substring in string in Java在Java中查找字符串中所有出现的子字符串
【发布时间】: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
  • 请使用更有意义的变量名。很难理解 cthing1outthingniwords 是什么意思。使用lastIndexindexList 之类的东西会更容易理解你写的内容并更正它。

标签: java regex string substring


【解决方案1】:

您可以在正向前瞻中使用捕获来获取所有重叠匹配,并使用Matcher#start 来获取捕获的子字符串的索引。

至于the regex,应该是这样的

(?=(aa))

在 Java 代码中:

String s = "aaaaaa";
Matcher m = Pattern.compile("(?=(aa))").matcher(s);
List<Integer> pos = new ArrayList<Integer>();
while (m.find())
{
    pos.add(m.start());
}
System.out.println(pos);

结果:

[0, 1, 2, 3, 4]

IDEONE demo

【讨论】:

    【解决方案2】:

    使用正则表达式绝对是查找子字符串的一个过于繁重的解决方案,如果您的子字符串包含特殊的正则表达式字符,例如.,这将是一个问题。这是改编自this answer的解决方案:

    String str = "helloslkhellodjladfjhello";
    String findStr = "hello";
    int lastIndex = 0;
    List<Integer> result = new ArrayList<Integer>();
    
    while(lastIndex != -1) {
    
        lastIndex = str.indexOf(findStr,lastIndex);
    
        if(lastIndex != -1){
            result.add(lastIndex);
            lastIndex += 1;
        }
    }
    

    【讨论】:

    • 这会为“aa”返回 [0,2,4] 而不是海报想要的 [0,1,2,3,4]。只需将 lastIndex 增加 1 而不是 findStr 的长度即可找到所有子匹配项。
    • 你是对的,忘记了重叠部分。编辑。
    猜你喜欢
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    相关资源
    最近更新 更多