strings.Split in Go

前端 未结 2 1920
南方客
南方客 2021-02-19 23:14

The file names.txt consists of many names in the form of:

\"KELLEE\",\"JOSLYN\",\"JASON\",\"INGER\",\"INDIRA\",\"GLINDA\",\"GLENNIS\"

Does anyo

相关标签:
2条回答
  • 2021-02-19 23:53

    Jeremy's answer is basically correct and does exactly what you have asked for. But the format of your "names.txt" file is actually a well known and is called CSV (comma separated values). Luckily, Go comes with an encoding/csv package (which is part of the standard library) for decoding and encoding such formats easily. In addition to your + Jeremy's solution, this package will also give exact error messages if the format is invalid, supports multi-line records and does proper unquoting of quoted strings.

    The basic usage looks like this:

    package main
    
    import (
        "encoding/csv"
        "fmt"
        "io"
        "os"
    )
    
    func main() {
        file, err := os.Open("names.txt")
        if err != nil {
            fmt.Println("Error:", err)
            return
        }
        defer file.Close()
        reader := csv.NewReader(file)
        for {
            record, err := reader.Read()
            if err == io.EOF {
                break
            } else if err != nil {
                fmt.Println("Error:", err)
                return
            }
    
            fmt.Println(record) // record has the type []string
        }
    }
    

    There is also a ReadAll method that might make your program even shorter, assuming that the whole file fits into the memory.

    Update: dystroy has just pointed out that your file has only one line anyway. The CSV reader works well for that too, but the following, less general solution should also be sufficient:

    for {
        if n, _ := fmt.Fscanf(file, "%q,", &name); n != 1 {
            break
        }
        fmt.Println("name:", name)
    }
    
    0 讨论(0)
  • 2021-02-20 00:03

    Split doesn't remove characters from the substrings. Your split is fine you just need to process the slice afterwards with strings.Trim(val, "\"").

    for i, val := range arr {
      arr[i] = strings.Trim(val, "\"")
    }
    

    Now arr will have the leading and trailing "s removed.

    0 讨论(0)
提交回复
热议问题