Add Locale-accepting overloads for (de)capitalize in JDK stdlib

#KT-28933 fixed
This commit is contained in:
Jake Wharton
2019-02-07 11:36:09 -05:00
committed by Ilya Gorbunov
parent f702417655
commit af31794f60
3 changed files with 65 additions and 0 deletions
@@ -567,6 +567,31 @@ public actual fun String.capitalize(): String {
return if (isNotEmpty() && this[0].isLowerCase()) substring(0, 1).toUpperCase() + substring(1) else this
}
/**
* Returns a copy of this string having its first letter uppercased preferring [Character.toTitleCase] (if different from
* [Character.toUpperCase]) or by [String.toUpperCase] using [locale], or the original string, if it's empty or already
* starts with an upper case letter.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public fun String.capitalize(locale: Locale): String {
if (isNotEmpty()) {
val firstChar = this[0]
if (firstChar.isLowerCase()) {
return buildString {
val titleChar = firstChar.toTitleCase()
if (titleChar != firstChar.toUpperCase()) {
append(titleChar)
} else {
append(this@capitalize.substring(0, 1).toUpperCase(locale))
}
append(this@capitalize.substring(1))
}
}
}
return this
}
/**
* Returns a copy of this string having its first letter lowercased, or the original string,
* if it's empty or already starts with a lower case letter.
@@ -577,6 +602,16 @@ public actual fun String.decapitalize(): String {
return if (isNotEmpty() && this[0].isUpperCase()) substring(0, 1).toLowerCase() + substring(1) else this
}
/**
* Returns a copy of this string having its first letter lowercased using [locale], or the original string,
* if it's empty or already starts with a lower case letter.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public fun String.decapitalize(locale: Locale): String {
return if (isNotEmpty() && this[0].isUpperCase()) substring(0, 1).toLowerCase(locale) + substring(1) else this
}
/**
* Returns a string containing this char sequence repeated [n] times.
* @throws [IllegalArgumentException] when n < 0.