
[英]Kotlin String max length? (Kotlin file with a long String is not compiling)
[英]Obtain the length of the selected string in kotlin
嗨,我想在字符串中找到索引字符或单词
例如 tv.text="嘿,你好吗,你还好吗"
值 res=tv.text.indexOf('h')
(有什么办法可以用字符串代替字符?
output res=0
仅返回第一个带有 h 的字符的索引,但在我的电视文本中,我有更多的 h 字符我们可以返回所有 h 字符索引吗
您可以使用filter
function 来获取具有所需字符的所有字符串索引。
val text = " hey how are you, are you okay"
val charToSearch = 'h'
val occurrences = text.indices.filter { text[it] == charToSearch }
println(occurences)
而且,如果你想搜索字符串而不是单个字符,你可以这样做:
text.indices.filter { text.startsWith(stringToSearch, it) }
以下应该可以工作(如果您在上一次迭代中找到一个索引,并且您从先前找到的字符实例加 1 开始后续迭代,则尝试查找索引,这样您就不会一次又一次地找到相同的索引):
fun main() {
val word = " hey how are you, are you okay"
val character = 'h'
var index: Int = word.indexOf(character)
while (index >= 0) {
println(index)
index = word.indexOf(character, index + 1)
}
}
如果要存储索引以供以后使用,还可以执行以下操作:
fun main() {
val word = " hey how are you, are you okay"
val character = 'h'
val indexes = mutableListOf<Int>()
var index: Int = word.indexOf(character)
while (index >= 0) {
index = word.indexOf(character, index + 1)
indexes.add(index)
}
println(indexes)
}
如果您只想让所有索引匹配一个字符,您可以这样做:
word.indices.filter { word[it] == 'h' }
查找字符串匹配比较棘手,您可以使用 Kotlin 的regionMatches function 来检查从index开始的字符串部分是否与您要查找的内容匹配:
val findMe = "you"
word.indices.filter { i ->
word.regionMatches(i, findMe, 0, findMe.length)
}
您也可以使用正则表达式,只要您小心验证搜索模式:
Regex(findMe).findAll(word)
.map { it.range.first() } // getting the first index of each matching range
.toList()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.