This code makes it easy to pluralize words based off of English pluralizing rules.
$ go run main.go
2 balls
1 boy
3 foxes
2 babies
1 leaf
3 knives
2 cats
1 dress| package main | |
| import ( | |
| "fmt" | |
| "strings" | |
| ) | |
| func pluralize(word string, count int) string { | |
| if count == 1 { | |
| return word | |
| } | |
| lastChar := word[len(word)-1] | |
| lastTwoChars := word[len(word)-2:] | |
| switch { | |
| case lastChar == 's' || lastChar == 'x' || lastChar == 'z' || | |
| (lastTwoChars == "ch" || lastTwoChars == "sh"): | |
| return word + "es" | |
| case lastTwoChars == "ay" || lastTwoChars == "ey" || lastTwoChars == "oy" || lastTwoChars == "uy": | |
| return word + "s" | |
| case lastChar == 'y' && !isVowel(word[len(word)-2]): | |
| return word[:len(word)-1] + "ies" | |
| case lastChar == 'y': | |
| return word + "s" | |
| case lastTwoChars == "fe" && len(word) > 2: | |
| return word[:len(word)-2] + "ves" | |
| case lastChar == 'f': | |
| return word[:len(word)-1] + "ves" | |
| default: | |
| return word + "s" | |
| } | |
| } | |
| func isVowel(char byte) bool { | |
| return strings.ContainsAny(string(char), "aeiouAEIOU") | |
| } | |
| func main() { | |
| word1 := "ball" | |
| word2 := "boy" | |
| word3 := "fox" | |
| word4 := "baby" | |
| word5 := "leaf" | |
| word6 := "knife" | |
| word7 := "cat" | |
| word8 := "dress" | |
| count1 := 2 | |
| count2 := 1 | |
| count3 := 3 | |
| fmt.Printf("%d %s\n", count1, pluralize(word1, count1)) // prints "2 balls" | |
| fmt.Printf("%d %s\n", count2, pluralize(word2, count2)) // prints "1 boy" | |
| fmt.Printf("%d %s\n", count3, pluralize(word3, count3)) // prints "3 foxes" | |
| fmt.Printf("%d %s\n", count1, pluralize(word4, count1)) // prints "2 babies" | |
| fmt.Printf("%d %s\n", count2, pluralize(word5, count2)) // prints "1 leaf" | |
| fmt.Printf("%d %s\n", count3, pluralize(word6, count3)) // prints "3 knives" | |
| fmt.Printf("%d %s\n", count1, pluralize(word7, count1)) // prints "2 cats" | |
| fmt.Printf("%d %s\n", count2, pluralize(word8, count2)) // prints "1 dress" | |
| } |