字符串匹配单词的第二和第三次出现

时间:2018-04-05 17:24:23

标签: java android string kotlin pattern-matching

我有一个stringSome =“这是一个字符串,它是一个字符串,它是一个新字符串。” wordList = [a,string,string,and,is]

我希望按顺序迭代它,它应该在给出索引时产生。

结果应该是顺序启动索引= 8,10,30,37,44

a,s,s,a,i

第一个也是唯一的索引很容易只调用indexof但是,我不确定如何继续搜索字符串是否重复。

val getIndicesOfAllWords: MutableList<Triple<String, Int, Int>> = mutableListOf()
val stringSome = "this is a string and it is a string and it is a new string."

val wordList = listOf<String>("a", "string", "string", "and", "is")
for (word in 0 until wordList.count()){
    val firstIndex = stringSome!!.indexOf(wordList[word])
    val matchLength = wordList[word].length
    getIndicesOfAllWords.add(Triple(wordList[word], firstIndex, matchLength))        
}

2 个答案:

答案 0 :(得分:0)

每次在HashMap中找到一个单词保存当前索引时,如果在该地图中找到它,则要搜索的每个单词从最后一个索引开始搜索+ 1,否则从头开始搜索。

答案 1 :(得分:0)

我想我可以通过以下代码找到答案。 如果有更好的解决方案,或者如果我做错了什么,请尽快优化,请提示。

val getIndicesOfAllWords: MutableList<Triple<String, Int, Int>> = mutableListOf()

for (word in 0 until wordList.count()){
    if (getIndicesOfAllWords.count()==0) {
        val firstIndex = desc!!.indexOf(wordList[word])
        val matchLength = wordList[word].length
        getIndicesOfAllWords.add(Triple(wordList[word], firstIndex, matchLength))
    } else{
        val firstIndex = desc!!.indexOf(wordList[word], getIndicesOfAllWords[word-1].second+1)
        val matchLength = wordList[word].length
        getIndicesOfAllWords.add(Triple(wordList[word], firstIndex, matchLength))
    }
}