dtv55860 2016-08-13 13:34
浏览 56
已采纳

将字符串数组的单个元素初始化为Go lang中的另一个字符串变量

In this code, I read a text file for input (A1,B2) and Im using the split function to separate them at comma and store in strs, according to the function definition its returns a array in this case it is strs array, i want the first element in strs to be in currentSource and the second element to be in CurrentDest.I tried printing both the variables individually to check if its working,but the program exits after that and I get a error saying Panic: index out of range. Can anybody help me out..!!!

var currentSource string
var currentDest string

func main() {

    file, err := os.Open("chessin.txt")
    if err != nil {
        fmt.Println(err)
    }
    defer file.Close()
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        strs := strings.Split(scanner.Text(), ",")

        currentSource = strs[0]
        currentDest = strs[1]
}
  • 写回答

2条回答 默认 最新

  • dongtong848825 2016-08-13 13:52
    关注

    This works

    var currentSource string
    var currentDest string
    
    func main() {
    
        file := "A1,B2
    "
        scanner := bufio.NewScanner(strings.NewReader(file))
        for scanner.Scan() {
            strs := strings.Split(scanner.Text(), ",")
    
            currentSource = strs[0]
            currentDest = strs[1]
    
            fmt.Println(strs)
        }
    
    
    }
    

    Are you sure your file (chessin.txt) it is ok?

    Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程