Extracting substrings in Go

后端 未结 7 706
甜味超标
甜味超标 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:54

    This is the simple one to perform substring in Go

    package main
    
    import "fmt"
    
    var p = fmt.Println
    
    func main() {
    
      value := "address;bar"
    
      // Take substring from index 2 to length of string
      substring := value[2:len(value)]
      p(substring)
    
    }
    
    0 讨论(0)
  • 2020-12-12 21:55

    To avoid a panic on a zero length input, wrap the truncate operation in an if

    input, _ := src.ReadString('\n')
    var inputFmt string
    if len(input) > 0 {
        inputFmt = input[:len(input)-1]
    }
    // Do something with inputFmt
    
    0 讨论(0)
  • 2020-12-12 21:58

    To get substring

    1. find position of "sp"

    2. cut string with array-logical

    https://play.golang.org/p/0Redd_qiZM

    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-12-12 22:01

    WARNING: operating on strings alone will only work with ASCII and will count wrong when input is a non-ASCII UTF-8 encoded character, and will probably even corrupt characters since it cuts multibyte chars mid-sequence.

    Here's a UTF-8-aware version:

    func substr(input string, start int, length int) string {
        asRunes := []rune(input)
    
        if start >= len(asRunes) {
            return ""
        }
    
        if start+length > len(asRunes) {
            length = len(asRunes) - start
        }
    
        return string(asRunes[start : start+length])
    }
    
    0 讨论(0)
  • 2020-12-12 22:15

    Go strings are not null terminated, and to remove the last char of a string you can simply do:

    s = s[:len(s)-1]
    
    0 讨论(0)
提交回复
热议问题