1 回答
TA贡献1796条经验 获得超4个赞
包缓冲区
func (*Reader) 读取字符串
func (b *Reader) ReadString(delim byte) (string, error)ReadString 一直读取到输入中第一次出现 delim,返回一个包含数据的字符串,直到并包括分隔符。如果 ReadString 在找到分隔符之前遇到错误,它会返回错误之前读取的数据和错误本身(通常是 io.EOF)。当且仅当返回的数据不以 delim 结尾时,ReadString 返回 err != nil。
返回包含数据的字符串,包括分隔符。
摆脱任何尾随换行符:"\n"
或"\r\n"
。要快速修复,请写:
sentence := strings.Split(strings.TrimSpace(sentenceraw), " ")
例如,
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
"github.com/stretchr/stew/slice"
)
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(strings.TrimSpace(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, " "))
}
输出:
Type what you would like translated into pig-latin and press ENTER: hello world
ellohay orldway
- 1 回答
- 0 关注
- 85 浏览
添加回答
举报