You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin技术问询:如何获取选中字符串长度及字符串中字符/单词的索引(含多匹配索引获取)

Kotlin字符串操作相关问题解答

嘿,我来帮你搞定这两个字符串操作的问题:

1. 如何在Kotlin中获取选中字符串的长度?

这个得分两种常见场景来看:

  • 如果是EditText控件中用户选中的文本:可以通过selectionStart和selectionEnd属性来计算长度,示例代码如下:
    val editText = findViewById<EditText>(R.id.editText)
    val start = editText.selectionStart
    val end = editText.selectionEnd
    val selectedLength = end - start
    // 注意:如果没有选中内容,start和end会相等,此时长度为0
    
  • 如果是普通字符串中你自行定义的选中范围(比如从索引startIndex到endIndex):直接用结束索引减去起始索引即可,前提是endIndex大于startIndex且在字符串的合法范围内:
    val str = "Hello Kotlin"
    val startIndex = 2
    val endIndex = 7
    val selectedLength = endIndex - startIndex // 结果为5,对应"llo K"的长度
    

2. 关于indexOf方法的两个疑问

先看你的示例代码:

tv.text=" hey how are you, are you okay"
val res=tv.text.indexOf('h')

疑问一:能否传入字符串而非字符作为indexOf的参数?

当然可以!Kotlin的String类提供了indexOf的重载方法,支持传入字符串参数,它会返回该子字符串第一次出现的起始索引。示例代码:

val str = " hey how are you, are you okay"
// 查找子字符串"how"第一次出现的索引
val index = str.indexOf("how") // 返回4

如果找不到对应的子字符串,方法会返回-1,这点和传入字符的版本一致。

疑问二:如何获取字符串中所有'h'字符的索引?

要收集所有匹配字符的索引,我们可以循环调用indexOf的重载方法,每次从上一次找到的索引位置的下一位开始查找,直到方法返回-1为止。示例代码:

val str = " hey how are you, are you okay"
val targetChar = 'h'
val allIndices = mutableListOf<Int>()
var currentIndex = str.indexOf(targetChar)

while (currentIndex != -1) {
    allIndices.add(currentIndex)
    // 从下一个位置继续查找
    currentIndex = str.indexOf(targetChar, currentIndex + 1)
}

// 输出所有'h'的索引:[0, 4]
println(allIndices)

如果要查找所有子字符串的索引,逻辑也是一样的,只需要把targetChar换成目标字符串即可。

内容的提问来源于stack exchange,提问作者Rahimian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:37:41