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
lenoperation : 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
1after 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]
Answer from Denys Séguret on Stack OverflowIt 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
lenoperation : 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
1after 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]
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:
// NOTE: this isn't multi-Unicode-codepoint aware, like specifying skintone or
// gender of an emoji: https://unicode.org/emoji/charts/full-emoji-modifiers.html
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])
}
Videos
I'm trying to find a substring in a title, but I don't know if I should go with regexp or strings library. I'm not looking for complex stuffs, only for a simple string match. I only need to be the most efficient way since I'm gonna use it on a slice, ty!