我必须编写一个函数,该函数计算子字符串在文本中出现的次数,并返回一个map (string - counts)
我尝试使用.contains来实现它,但是它不能在一个单词中计算多次出现的次数(“lalala”中的“la”),现在我被如何修复它所困扰。
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个字符子串。
发布于 2020-08-08 06:04:46
使用indexOf从给定的起始位置查找第一个匹配项的位置,如果未找到匹配项,则使用-1。在此之后,您可以更改开始位置,并再次重复。那么你就不会有重叠的问题了。
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
}但你应该知道两件事:
发布于 2019-05-27 00:13:39
我的意思是,StringUtils.html#countMatches是Apache commons的一部分。
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") = 0https://stackoverflow.com/questions/56315214
复制相似问题