我想獲取字串中的索引字符或單詞
例如
tv.text=" hey how are you, are you okay"
val res=tv.text.indexOf('h')
(有什么辦法可以把字串而不是字符?
輸出解析度=0
只回傳帶有 h 的第一個字符的索引,但在我的電視文本中我有更多的 h 個字符,我們可以回傳所有的 h 個字符索引嗎
uj5u.com熱心網友回復:
您可以使用filter函式來獲取具有所需字符的所有字串索引。
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) }
uj5u.com熱心網友回復:
以下應該有效(如果您在前一次迭代中找到一個索引,并且您從先前找到的字符實體加 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)
}
uj5u.com熱心網友回復:
如果您只想要所有與字符匹配的索引,您可以這樣做:
word.indices.filter { word[it] == 'h' }
查找字串匹配比較棘手,您可以使用 Kotlin 的regionMatches函式來檢查從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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/361544.html
標籤:科特林 子串 指数 android-studio-3.0
上一篇:如何將引數輸入用于物件參考?
