Extracting substrings in Go

后端 未结 7 796
甜味超标
甜味超标 2020-12-12 21:12

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, s

7条回答
  •  再見小時候
    2020-12-12 21:59

    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

    inputFmt:=input[:len(input)-1]
    

提交回复
热议问题