Extracting substrings in Go

后端 未结 7 821
甜味超标
甜味超标 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 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])
    }
    

提交回复
热议问题