【问题标题】:Obtain the length of the selected string in kotlin获取kotlin中选中字符串的长度
【发布时间】:2021-12-30 07:20:54
【问题描述】:

我想获取字符串中的索引字符或单词

例如

tv.text=" hey how are you, are you okay"

val res=tv.text.indexOf('h')

(有什么办法可以把字符串代替char吗?

输出 res=0

仅返回第一个带有 h 的字符的索引,但在我的电视文本中,我有更多的 h 字符 我们可以返回所有 h 字符索引

【问题讨论】:

    标签: kotlin substring indexof android-studio-3.0


    【解决方案1】:

    您可以使用filter 函数来获取具有所需字符的所有字符串索引。

    val text = " hey how are you, are you okay"
    val charToSearch = 'h'
    val occurrences = text.indices.filter { text[it] == charToSearch }
    println(occurences)
    

    Try it yourself

    而且,如果你想搜索字符串而不是单个字符,你可以这样做:

    text.indices.filter { text.startsWith(stringToSearch, it) }
    

    【讨论】:

    • 这实际上是一个更好的方法! ;)
    【解决方案2】:

    以下应该可以工作(如果您在上一次迭代中找到一个索引,则尝试查找索引,然后从之前找到的字符实例加 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)
    }
    

    【讨论】:

      【解决方案3】:

      如果您只想让所有索引匹配一个字符,您可以这样做:

      text.indices.filter { text[it] == 'h' }
      

      查找字符串匹配比较棘手,您可以使用 Kotlin 的 regionMatches 函数来检查从 index 开始的字符串部分是否与您要查找的内容匹配:

      val findMe = "you"
      text.indices.filter { i ->
          text.regionMatches(i, findMe, 0, findMe.length)
      }
      

      您也可以使用正则表达式,只要您小心验证搜索模式:

      Regex(findMe).findAll(text)
          .map { it.range.first() } // getting the first index of each matching range
          .toList()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-20
        • 1970-01-01
        • 1970-01-01
        • 2020-09-17
        • 2012-05-02
        相关资源
        最近更新 更多