字符串.在Go中拆分 [英] strings.Split in Go

查看:50
本文介绍了字符串.在Go中拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件names.txt由许多名称组成,格式为:

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

有人知道如何分割字符串,以便用逗号分隔各个名称吗?

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

以下代码用逗号分割,并在名称周围加上引号,什么是转义字符以分割出".可以在一个Split语句中完成,分割出","并用逗号分隔?

 程序包主要导入"fmt"导入"io/ioutil"导入字符串"func main(){fData,err:= ioutil.ReadFile("names.txt")//读取外部文件如果err!= nil {fmt.Println("Err is",err)//打印任何错误}strbuffer:= string(fData)//将读入的文件转换为字符串arr:= strings.Split(strbuffer,,")fmt.Println(arr)} 

顺便说一句,这是Project Euler问题#22的一部分. http://projecteuler.net/problem=22

解决方案

Jeremy的回答基本上是正确的,并且完全符合您的要求.但是"names.txt"文件的格式实际上是众所周知的,称为 CSV (用逗号分隔的值).幸运的是,Go随附了 encoding/csv 包(属于标准库),用于对此类格式进行解码和编码容易地.除了您的+ Jeremy的解决方案之外,如果格式无效,支持多行记录并且对引用的字符串进行正确的取消引用,此软件包还将提供确切的错误消息.

基本用法如下:

 程序包主要进口 (编码/csv""fmt""io""os")func main(){文件,错误:= os.Open("names.txt")如果err!= nil {fmt.Println("Error:",err)返回}延迟file.Close()reader:= csv.NewReader(文件)为了 {记录,错误:= reader.Read()如果err == io.EOF {休息} if err!= nil {fmt.Println("Error:",err)返回}fmt.Println(record)//记录的类型为[] string}} 

还有一个 ReadAll 方法,它可能会使您的程序变得更短,假设整个过程文件适合内存.

更新:dystroy刚刚指出您的文件只有一行.CSV阅读器也可以很好地工作,但是以下通用性较低的解决方案也应该足够了:

<{如果n,_:= fmt.Fscanf(file,%q,",& name);n!= 1 {休息}fmt.Println(名称:",名称)}

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

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

Does anyone know how to split the string so that it is individual names separated by commas?

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

The following code splits by comma and leaves quotes around the name, what is the escape character to split out the ". Can it be done in one Split statement, splitting out "," and leaving a comma to separate?

package main

import "fmt"
import "io/ioutil"
import "strings"

func main() {
        fData, err := ioutil.ReadFile("names.txt")  // read in the external file
    if err != nil {
        fmt.Println("Err is ", err)     // print any error
    }
    strbuffer := string(fData)  // convert read in file to a string

    arr := strings.Split(strbuffer, ",")

    fmt.Println(arr)

}

By the way, this is part of Project Euler problem # 22. http://projecteuler.net/problem=22

解决方案

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

这篇关于字符串.在Go中拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆