-1

this is my/his house - Input

This Is My/His House - Output

In Swift ,there is capitalized method which gives the above output ,is there any way to achieve the same in kotlin

  • Does this answer your question? [Capitalise every word in String with extension function](https://stackoverflow.com/questions/52042903/capitalise-every-word-in-string-with-extension-function) – Morrison Chang May 19 '23 at 05:45

3 Answers3

1

In Kotlin

val s = "this is my/his house"
println(s.toCapitalizeEachWord())

Extension Function:

fun String.toCapitalizeEachWord() : String{
return this.split(" ").map {
    if(it.contains("/")){
        it.split("/").map { word -> word.replaceFirstChar { firstChar -> firstChar.uppercase() }
        }.joinToString("/")
    }else{
        it.replaceFirstChar { firstChar -> firstChar.uppercase() }
    }
}.joinToString(" ") }

Input: this is my/his house

Output: This Is My/His House

Tippu Fisal Sheriff
  • 2,177
  • 11
  • 19
0

You have to capitalize every word.

However String.capitalize() is now deprecated.

The easer solution is:

    fun String.capitalizeSentence(): String =
        this.trim().split("\\s+".toRegex())
            .joinToString(" ") { it.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() } }
0

Well many has posted correct core logic or main logic so you just needed to add little bit your own logic to work . Anyways below method is tested with your requirement and it is working fine

fun String.capitalizeEachWord() : String{
    return this.split(" ").map {
        if(it.contains("/")){
            it.split("/").map { word -> word.replaceFirstChar { firstChar -> firstChar.uppercase() }
             }.joinToString("/")
        }else{
            it.replaceFirstChar { firstChar -> firstChar.uppercase() }
        }
    }.joinToString(" ")
}
jayesh gurudayalani
  • 1,368
  • 1
  • 9
  • 14