For Loop iteration over string slice doesn't work

后端 未结 1 1990
日久生厌
日久生厌 2020-12-20 07:03

I wrote this code, which should translate a lower case english phrase into pig latin.

package main

import (
    \"fmt\"
    \"strings\"
    \"bufio\"
    \"         


        
相关标签:
1条回答
  • 2020-12-20 07:58

    Package bufio

    func (*Reader) ReadString

    func (b *Reader) ReadString(delim byte) (string, error)
    

    ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim.


    returning a string containing the data up to and including the delimiter.

    Get rid of any trailing newlines: "\n" or "\r\n". For a quick fix, write:

    sentence := strings.Split(strings.TrimSpace(sentenceraw), " ")
    

    For example,

    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, " "))
    }
    

    Output:

    Type what you would like translated into pig-latin and press ENTER: hello world
    ellohay orldway
    
    0 讨论(0)
提交回复
热议问题