I implemented a custom rsplit
function in Scala to imitate Python's rsplit
.
The concept behind it involves iteratively using lastIndexOf
and substring
to perform rsplit
.
object Main {
def rsplit(string: String, delimiter: String, maxSplits: Int): Array[String] = {
var remainingSplits = maxSplits
var str = string
var result = List[String]()
while (remainingSplits > 0) {
val pos = str.lastIndexOf(delimiter)
if (pos == -1) {
result = str :: result
remainingSplits = 0
str=""
} else {
result = str.substring(pos + delimiter.length) :: result
str = str.substring(0, pos)
remainingSplits -= 1
}
}
if (str.nonEmpty || maxSplits == 0) {
result = str :: result
}
result.toArray
}
def myPrint(stringArray: Array[String]): Unit= {
println("["++stringArray.map("\'"++_++"\'").mkString(", ")++"]");
}
def main(args: Array[String]): Unit = {
// Test cases
myPrint(rsplit("bor tor tor tor", "tor", 2)) // More than maxSplits
myPrint(rsplit("bor tor tor", "tor", 2)) // Exactly equal to maxSplits
myPrint(rsplit("bor tor", "tor", 2)) // Less than maxSplits
}
}
Attempt This Scala code Online!
print("bor tor tor tor".rsplit("tor", 2)) # ['bor tor ', ' ', '']
print("bor tor tor".rsplit("tor", 2)) # ['bor ', ' ', '']
print("bor tor".rsplit("tor", 2)) # ['bor ', '']
Run the reference Python code online!
lastIndexOf
can return-1
. – Inca