我是Kotlin的新手。我想知道split函数的工作方式。请参见下面的示例。
示例1:
var str = "Kotlin TutorialsEPTutorialaSEpKartSEpExamples"
var delimiter1 = "SEP"
var delimiter2 = "ASEP"
var delimiter3 = "ASEPP"
val parts = str.split(delimiter1, ignoreCase = true)
print(parts)
输出为(有效-基于“ SEP”字符串的所有理解都将被拆分):
[Kotlin Tutorial, Tutoriala, Kart, Examples]
示例2:
var str = "Kotlin TutorialsEPTutorialaSEpKartSEpExamples"
var delimiter1 = "SEP"
var delimiter2 = "ASEP"
var delimiter3 = "ASEPP"
val parts = str.split(delimiter1,delimiter2,ignoreCase = true)
print(parts)
输出是(正在工作-理解为全部,基于“ SEP”和“ ASEP”字符串将被拆分,但是我不知道它是如何工作的。使用“ SEP”拆分后,只有TutorialA会出现。但是aSEP如何正在分裂?):
[Kotlin Tutorial, Tutorial, Kart, Examples]
示例3:
var str = "Kotlin TutorialsEPTutorialaSEpKartSEpASEPPExamples"
var delimiter1 = "SEP"
var delimiter2 = "ASEP"
var delimiter3 = "ASEPP"
val parts = str.split(delimiter1,delimiter2,delimiter3,ignoreCase = true)
输出:根据第二个示例,ASEPP应该被分割吗?
[Kotlin Tutorial, Tutorial, Kart, , PExamples]
请参阅P即将到来。请解释逻辑?
答案 0 :(得分:2)
不,您的问题是CharSequence.split(...)“获取”您的所有分隔符,而using循环仅遍历您的字符串并删除当前迭代中等于分隔符的字符(vararg分隔符)。如果您在delimeter2之前写了delimeter3,那么您会得到正确的结果(在您看来)
val str = "Kotlin TutorialsEPTutorialaSEpKartSEpASEPPExamples"
val delimiter1 = "SEP"
val delimiter2 = "ASEP"
val delimiter3 = "ASEPP"
val parts = str.split(delimiter1, delimiter3, delimiter2, ignoreCase = true)
println(parts)
输出
[Kotlin Tutorial, Tutorial, Kart, , Examples]