我写了这段代码,它应该将一个小写的英语短语翻译成 pig latin。
package main
import (
"fmt"
"strings"
"bufio"
"github.com/stretchr/stew/slice"
"regexp"
"os"
)
func main() {
lst := []string{"sh", "gl", "ch", "ph", "tr", "br", "fr", "bl", "gr", "st", "sl", "cl", "pl", "fl", "th"}
reader := bufio.NewReader(os.Stdin)
fmt.Print("Type what you would like translated into pig-latin and press ENTER: ")
sentenceraw, _ := reader.ReadString('\n')
sentence := strings.Split(sentenceraw, " ")
isAlpha := regexp.MustCompile(`^[A-Za-z]+$`).MatchString
newsentence := make([]string, 0)
for _, i := range sentence {
if slice.Contains([]byte{'a', 'e', 'i', 'o', 'u'}, i[0]) {
newsentence = append(newsentence, strings.Join([]string{string(i), "ay"}, ""))
} else if slice.Contains(lst, string(i[0])+string(i[1])) {
newsentence = append(newsentence, strings.Join([]string{string(i[2:]), string(i[:2]), "ay"}, ""))
} else if !isAlpha(string(i)) {
newsentence = append(newsentence, strings.Join([]string{string(i)}, ""))
} else {
newsentence = append(newsentence, strings.Join([]string{string(i[1:]), string(i[0]), "ay"}, ""))
}
}
fmt.Println(strings.Join(newsentence, " "))
}
但是,它无法对短语中的最后一个单词执行任何操作。
如果我使用句子“the quick brown fox jumped over the lazy dog”我得到“ethay uickqay ownbray oxfay umpedjay overay ethay azylay dog”
这里的一切都是对的,除了最后一句话!为什么它不起作用?如果我使用“hello world”作为我的短语,也会发生同样的事情。
慕的地8271018
相关分类