dsfds2343 2018-04-15 14:55
浏览 86

Golang解析数组

I am trying to figure out why my code is not working. I wish to take a slice of numbers and strings, and separate it into three slices. For each element in the slice, if it is a string, append it to the strings slice, and if it is a positive number, append it to the positive numbers, and likewise with negative. Yet, here is the output

Names: EvTremblay 45.39934611083154 -75.71148292845268

[Crestview -75.73795670904249 BellevueManor -75.73886856878032 Dutchie'sHole -75.66809864107668 ...

Positives:[45.344387632924054 45.37223315413918 ... ] Negatives: []

Here is my code. Can someone tell me what is causing the Negatives array to not have any values?

func main() {
    fmt.Printf("%q
", strings.Split("a,b,c", ","))
    var names []string
    var positives, negatives []float64
    bs, err := ioutil.ReadFile("poolss.txt")
    if err != nil {
        return
    }
    str := string(bs)
    fmt.Println(str)
    tokens := strings.Split(str, ",")
    for _, token := range tokens {
        if num, err := strconv.ParseFloat(token, 64); err == nil {
            if num > 0 {
                positives = append(positives, num)
            } else {
                negatives = append(negatives, num)
            }

        } else {
            names = append(names, token)
        }

    fmt.Println(token)
    }

    fmt.Println(fmt.Sprintf("Strings: %v",names))
    fmt.Println(fmt.Sprintf("Positives: %v", positives))
    fmt.Println(fmt.Sprintf("Negatives: %v",negatives))
    for i := range names{
        fmt.Println(names[i])

        fmt.Println(positives[i])

        fmt.Println(negatives[i])
    }
}
  • 写回答

3条回答 默认 最新

  • dongmeiba6151 2018-04-15 15:23
    关注

    Your code has strings as a variable name:

    var strings []string
    

    and strings as a package name:

    tokens := strings.Split(str, ",")
    

    Don't do that!

    strings.Split undefined (type []string has no field or method Split)
    

    Playground: https://play.golang.org/p/HfZGj0jOT-P

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大