#2898 title() Case method

Gary Fri 1 Dec 2023

I was wondering if Fantom has a title() method similar to Python which transforms the first letter in each word into upper case and the rest of characters into lower case.

I suspect not after perusing the docs. But since I'm learning Fantom, I decided to take the opportunity to translate some Java code into Fantom. I believe it works. If any of the pros can share how I might improve it, I'd appreciate it. Functional programming is not my strong suit. :->

class GetRangeTest {

    static Void main() {
        input := "heLlO wOrLd of fAnToM!"
        
        words := input.split()
        output := ""
        
        words.each |Str word| {
          output += word[0..0].upper + 
                    word[1..-1].lower + " "
        }       
        echo(output)
    }
    
}

Henry Fri 1 Dec 2023

Hi chikega,

The most consistent way is probably just to call lower then capitalize

Something like this would be a common Fantom version of your code snippet there.

static Void main() {
    input := "heLlO wOrLd of fAnToM!"
    
    output := input.split().map { it.lower.capitalize }.join(" ")
    echo(output)
}

If you really wanted to squish it down, it could easily be a single line method as such:

Str capitalizeAll(Str input) { input.split.map { it.lower.capitalize }.join(" ") }

Should you wish you could also pass in an optional split character, and/or a string to use when re-assembling the string again

Str capitalizeAll(Str input, Int? splitChar := null, Str joinStr := " ") {
    input.split(splitChar).map { it.lower.capitalize }.join(joinStr)
}

Gary Fri 1 Dec 2023

What can I say, Henry? But just .. wow! So very clean and terse. Thank you! I took the liberty of making a compilable example for any other noobs learning Fantom. :-> Cheers, Gary

class CapitalizeTest {
    static Void main() {

        input := "heLlO wOrLd, of fAnToM!"
        echo (capitalizeAll(input))
        echo (capitalizeAll2(input, ','))

    }

    static Str capitalizeAll(Str input) { input.split.map { it.lower.capitalize }.join(" ") }

    static Str capitalizeAll2(Str input, Int? splitChar := null, Str joinStr := " ") {
        input.split(splitChar).map { it.lower.capitalize }.join(joinStr)
    }
}

Login or Signup to reply.