首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >统计给定的子串在文件中出现的次数

统计给定的子串在文件中出现的次数
EN

Stack Overflow用户
提问于 2019-05-27 00:08:19
回答 2查看 2.2K关注 0票数 2

我必须编写一个函数,该函数计算子字符串在文本中出现的次数,并返回一个map (string - counts)

我尝试使用.contains来实现它,但是它不能在一个单词中计算多次出现的次数(“lalala”中的“la”),现在我被如何修复它所困扰。

代码语言:javascript
复制
fun countSubstrings(inputName: String, substrings: List<String>): Map<String, Int> {

    val map = mutableMapOf<String, Int>()
    var tempCounter = 0
    for (i in 0 until substrings.size) {

        for (line in File(inputName).readLines()) {

            for (word in line.split(" ")) {
                if (word.contains(substrings[i], true)) tempCounter++ 
            }
        }
        map.put(substrings[i], tempCounter)
        tempCounter = 0
    }
    return map
}

所以,我希望这个函数能计算单词,2-3个字符子串,甚至1个字符子串。

EN

回答 2

Stack Overflow用户

发布于 2020-08-08 06:04:46

使用indexOf从给定的起始位置查找第一个匹配项的位置,如果未找到匹配项,则使用-1。在此之后,您可以更改开始位置,并再次重复。那么你就不会有重叠的问题了。

代码语言:javascript
复制
fun countMatches(text: String, template: String): Int {
    var cnt = 0
    var pos = 0
    while (true) {
        pos = text.indexOf(template, pos)
        if (pos != -1) {
            cnt++
            pos++
        } else {
            return cnt
        }
    }
}


fun countSubstrings(inputName: String, substrings: List<String>): Map<String, Int> {
    val mp = substrings.map { it to 0 }.toMap().toMutableMap()
    for (line in File(inputName).readLines()) {
        for (str in substrings) {
            if (str in mp) {
                mp[str] = (mp[str] ?: 0) + countMatches(line.toLowerCase(), str.toLowerCase())
            }
        }
    }
    return mp
}

但你应该知道两件事:

  1. 时间复杂度if O(n*m)其中n和m长度的这样的字符串。
  2. 这不是一个非常优雅的解决方案,可能存在更好的解决方案。But it works=)
票数 0
EN

Stack Overflow用户

发布于 2019-05-27 00:13:39

我的意思是,StringUtils.html#countMatches是Apache commons的一部分。

代码语言:javascript
复制
 StringUtils.countMatches(null, *)       = 0
 StringUtils.countMatches("", *)         = 0
 StringUtils.countMatches("abba", null)  = 0
 StringUtils.countMatches("abba", "")    = 0
 StringUtils.countMatches("abba", "a")   = 2
 StringUtils.countMatches("abba", "ab")  = 1
 StringUtils.countMatches("abba", "xxx") = 0
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56315214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档