Home > Enterprise >  How to capitalise first letter of each word in a string in go manually?
How to capitalise first letter of each word in a string in go manually?

Time:12-09

I am trying to write a function manually that capitalises the first letter of each word in a string. For example: "My dog is cute! I love my dog 4ever" to "My Dog Is Cute! I Love My Dog 4ever". I would be glad if you can help me.

func Capitalize(s string) string {
L := ToLower(s)
runeL := []rune(L)
len := len(runeL) - 1
Lnew := Concat(ToUpper(string(L[0])), string(runeL[1:len]))
LnewS := []rune(Lnew)
newstrings := []rune{}
for i := range LnewS {
    if IsAlpha(string(LnewS[i])) == true {
        newstrings = append(newstrings, LnewS[i])
    } else {
        newstrings = append(newstrings, LnewS[i])
        if LnewS[i 1] == rune(32) {
            newstrings = append(newstrings)
        }
        if IsLower(string(LnewS[i 1:])) {
            LnewS[i 1] = LnewS[i 1] - rune(32)
        }
    }
}
return string(newstrings)

}

CodePudding user response:

In a letter to Robert Hooke in 1675, Isaac Newton made his most famous statement: “If I have seen further it is by standing on the shoulders of Giants”.

Let's follow Newton's advice and read,

The C Programming Language, Second Edition
Brian W. Kernighan and Dennis M. Ritchie

In particular, read,

1.5.4 Word Counting

The section introduces a key concept, state variables: "The variable state records whether the program is currently in a word or not."

If we apply that insight to your problem then we get something like this,

package main

import (
    "fmt"
    "unicode"
)

func Capitalize(s string) string {
    rs := []rune(s)
    inWord := false
    for i, r := range rs {
        if unicode.IsLetter(r) || unicode.IsNumber(r) {
            if !inWord {
                rs[i] = unicode.ToUpper(r)
            }
            inWord = true
        } else {
            inWord = false
        }
    }
    return string(rs)
}

func main() {
    s := "My dog is cute! I love my dog 4ever"
    fmt.Println(s)
    t := Capitalize(s)
    fmt.Println(t)
}

https://go.dev/play/p/ZIkg44o8Brp

My dog is cute! I love my dog 4ever
My Dog Is Cute! I Love My Dog 4ever

CodePudding user response:

You can use the strings package with its title function to capitalize first letter of each word. An example of it can be seen below.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)


func main() {
    var strInput string
    fmt.Println("Enter a string")
    scanner := bufio.NewScanner(os.Stdin)
    if scanner.Scan() {
        strInput = scanner.Text()
    }

    res := strings.Title(strInput)
    fmt.Println(res)
}

If you wanna do it manually, write an algorithm where

  • Checks the entire index of the string
  • If an index is the first index or it's an alphabet after a space, change that index alphabet into uppercase, and it should work
  • Related