Skip to content

Instantly share code, notes, and snippets.

@MarkNjunge
Last active February 3, 2019 16:25
Show Gist options
  • Save MarkNjunge/5f3efb15719cc861be93a7985416e23c to your computer and use it in GitHub Desktop.
Save MarkNjunge/5f3efb15719cc861be93a7985416e23c to your computer and use it in GitHub Desktop.
var text = editText.text.toString()
// Save the original text without the tags
val original = text.replace(spoilerTag, "")
// Get the character ranges
val ranges = mutableListOf<Pair<Int, Int>>()
while (text.contains(spoilerTag)) {
// Get start and end of spoiler tags
val start = text.indexOf(spoilerTag)
val end = text.indexOf(spoilerTag, start + spoilerTag.length) - spoilerTag.length
ranges.add(Pair(start, end))
// Remove starting spoiler tags
// This is intentionally done before checking if an end tag exists to prevent an infinite loop
text = text.replaceRange(start, start + spoilerTag.length, "")
// If there is no end tag, the text was badly formatted
if (end <= start) continue
// Remove ending spoiler tags
text = text.replaceRange(end, end + spoilerTag.length, "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment