【问题标题】:Best way to get all character indexes for a given phrase located in text获取文本中给定短语的所有字符索引的最佳方法
【发布时间】:2012-01-02 06:09:57
【问题描述】:

获取给定文本字符串的搜索短语的所有字符位置的最佳方法是什么?

例如,假设我们有"the red cat is watching the red car stopped at the red stop sign"

输入:“红色” 输出:[5、29、52]

【问题讨论】:

    标签: java regex string-matching indexof


    【解决方案1】:

    可以使用字符串类的indexOf方法:

    String haystack = "the red cat is watching the red car stopped at the red stop sign";
    String needle = "red";
    int idx = 0, pos;
    while( (pos = haystack.indexOf(needle,idx)) != -1) {
            System.out.println(pos+1);
            idx += pos+1;     
    }
    

    See it

    【讨论】:

    • 感谢您帮我找到丢失的针头! ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 2010-09-27
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多