donglisi8644 2012-09-07 02:43
浏览 329


I'm trying to read an entire line from the console (including whitespace), then process it. Using bufio.ReadString, the newline character is read together with the input, so I came up with the following code to trim the newline character:

inputFmt:=input[0:len(input)-2]+"" //Need to manually add end of string

Is there a more idiomatic way to do this? That is, is there already a library that takes care of the ending null byte when extracting substrings for you?

(Yes, I know there is already a way to read a line without the newline character in go readline -> string but I'm looking more for elegant string manipulation.)

  • 写回答

6条回答 默认 最新

  • dougan1465 2012-09-07 07:39

    It looks like you're confused by the working of slices and the string storage format, which is different from what you have in C.

    • any slice in Go stores the length (in bytes), so you don't have to care about the cost of the len operation : there is no need to count
    • Go strings aren't null terminated, so you don't have to remove a null byte, and you don't have to add 1 after slicing by adding an empty string.

    To remove the last char (if it's a one byte char), simply do

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 咨询一下有关于王者荣耀赢藏战绩
  • ¥100 求购一套带接口实现实习自动签到打卡
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?