StringExtensions.kt 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package eu.kanade.tachiyomi.util.lang
  2. import net.greypanther.natsort.CaseInsensitiveSimpleNaturalComparator
  3. import kotlin.math.floor
  4. /**
  5. * Replaces the given string to have at most [count] characters using [replacement] at its end.
  6. * If [replacement] is longer than [count] an exception will be thrown when `length > count`.
  7. */
  8. fun String.chop(count: Int, replacement: String = "…"): String {
  9. return if (length > count) {
  10. take(count - replacement.length) + replacement
  11. } else {
  12. this
  13. }
  14. }
  15. /**
  16. * Replaces the given string to have at most [count] characters using [replacement] near the center.
  17. * If [replacement] is longer than [count] an exception will be thrown when `length > count`.
  18. */
  19. fun String.truncateCenter(count: Int, replacement: String = "..."): String {
  20. if (length <= count) {
  21. return this
  22. }
  23. val pieceLength: Int = floor((count - replacement.length).div(2.0)).toInt()
  24. return "${take(pieceLength)}$replacement${takeLast(pieceLength)}"
  25. }
  26. /**
  27. * Case-insensitive natural comparator for strings.
  28. */
  29. fun String.compareToCaseInsensitiveNaturalOrder(other: String): Int {
  30. val comparator = CaseInsensitiveSimpleNaturalComparator.getInstance<String>()
  31. return comparator.compare(this, other)
  32. }
  33. /**
  34. * Returns the size of the string as the number of bytes.
  35. */
  36. fun String.byteSize(): Int {
  37. return toByteArray(Charsets.UTF_8).size
  38. }
  39. /**
  40. * Returns a string containing the first [n] bytes from this string, or the entire string if this
  41. * string is shorter.
  42. */
  43. fun String.takeBytes(n: Int): String {
  44. val bytes = toByteArray(Charsets.UTF_8)
  45. return if (bytes.size <= n) {
  46. this
  47. } else {
  48. bytes.decodeToString(endIndex = n).replace("\uFFFD", "")
  49. }
  50. }