Created
May 1, 2022 21:17
-
-
Save hnOsmium0001/af3b80a8ed753f89daea7dca83c38b45 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StringView( | |
val string: String, | |
val offset: Int, | |
val length: Int, | |
) : Iterable<Char> { | |
constructor(string: String) : this(string, 0, string.length) | |
init { | |
val end = offset + length | |
assert(offset >= 0 && offset < string.length) | |
assert(end <= string.length) | |
} | |
override fun iterator() = StringViewIterator(this) | |
operator fun get(idx: Int) = string[offset + idx] | |
fun substring(offset: Int, length: Int): StringView { | |
return StringView(string, this.offset + offset, length) | |
} | |
fun startsWith(pattern: StringView): Boolean { | |
if (pattern.length > this.length) { | |
return false | |
} | |
for (i in 0 until pattern.length) { | |
if (this[i] != pattern[i]) { | |
return false | |
} | |
} | |
return true | |
} | |
fun endsWith(pattern: StringView): Boolean { | |
if (pattern.length > this.length) { | |
return false | |
} | |
val idxDelta = this.length - pattern.length | |
for (i in (pattern.length - 1) downTo 0) { | |
if (this[i + idxDelta] != pattern[i]) { | |
return false | |
} | |
} | |
return true | |
} | |
} | |
class StringViewIterator(private val stringView: StringView) : Iterator<Char> { | |
var offset: Int = 0 | |
override fun hasNext(): Boolean = offset < stringView.length | |
override fun next(): Char { | |
val result = stringView.string[stringView.offset + offset] | |
offset++ | |
return result | |
} | |
} | |
fun String.view() = StringView(this) | |
fun String.subView(offset: Int, length: Int) = StringView(this, offset, length) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment