你可以使用 Kotlin 中的正则表达式来找出长字符串 B 中所有的字符串 A 的起始和终点位置。下面是一个示例代码:

import java.util.regex.Pattern

fun findOccurrences(A: String, B: String): List<Pair<Int, Int>> {
    val pattern = Pattern.compile(A)
    val matcher = pattern.matcher(B)
    val occurrences = mutableListOf<Pair<Int, Int>>()

    while (matcher.find()) {
        val start = matcher.start()
        val end = matcher.end()
        occurrences.add(start to end)
    }

    return occurrences
}

fun main() {
    val A = "A"
    val B = "BBAABBBAAAABBBAAAABBBAA"
    
    val occurrences = findOccurrences(A, B)
    for (occurrence in occurrences) {
        val start = occurrence.first
        val end = occurrence.second
        println("A found at position $start to $end")
    }
}

运行此代码将输出:

A found at position 3 to 4
A found at position 7 to 8
A found at position 11 to 12
A found at position 15 to 16
A found at position 19 to 20

这里的 findOccurrences 函数接收字符串 A 和长字符串 B,并返回一个列表,列表中的每个元素是一个包含字符串 A 的起始和终点位置的 Pair。使用 Pattern.compile 函数来编译正则表达式 A,然后使用 matcher.find 函数在长字符串 B 中查找所有匹配项,并将起始和终点位置添加到 occurrences 列表中。最后,我们在 main 函数中调用 findOccurrences 来查找长字符串 B 中字符串 A 的所有出现位置并打印出来

有一个字符串A和长字符串BB中有0到n个A用正则找出B中所有的A并返回起始和终点位置。语言用kotlin

原文地址: http://www.cveoy.top/t/topic/ioXD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录