英文:
Why TrimLeft doesn't work as expected?
问题
我预期标签应该是"account",但实际上是"ccount"。为什么"a"被移除了?
package main
import "fmt"
import "strings"
func main() {
s := "refs/tags/account"
tag := strings.TrimLeft(s, "refs/tags")
fmt.Println(tag)
}
英文:
I've expected tag to be "account" but it is "ccount". Why is "a" removed?
package main
import "fmt"
import "strings"
func main() {
s := "refs/tags/account"
tag := strings.TrimLeft(s, "refs/tags")
fmt.Println(tag)
}
答案1
得分: 12
使用TrimPrefix而不是TrimLeft
package main
import "fmt"
import "strings"
func main() {
s := "refs/tags/account"
tag := strings.TrimPrefix(s, "refs/tags/")
fmt.Println(tag)
}
请注意,以下的TrimLeft调用将得到相同的字符串"fghijk":
package main
import (
"fmt"
"strings"
)
func main() {
s := "/abcde/fghijk"
tag := strings.TrimLeft(s, "/abcde")
fmt.Println(tag)
tag = strings.TrimLeft(s, "/edcba")
fmt.Println(tag)
}
所以TrimLeft不是适合你需求的方法。我猜在你给出的示例中使用它无法得到你期望的结果。
英文:
Use TrimPrefix instead of TrimLeft
package main
import "fmt"
import "strings"
func main() {
s := "refs/tags/account"
tag := strings.TrimPrefix(s, "refs/tags/")
fmt.Println(tag)
}
Please notice that following TrimLeft calls will result the same "fghijk
" string:
package main
import (
"fmt"
"strings"
)
func main() {
s := "/abcde/fghijk"
tag := strings.TrimLeft(s, "/abcde")
fmt.Println(tag)
tag = strings.TrimLeft(s, "/edcba")
fmt.Println(tag)
}
So TrimLeft is not the method which fits your needs. I guess it's impossible to use it in the example you've given to get the result you expect.
答案2
得分: 10
根据文档的描述,它正在按预期工作:
TrimLeft 返回字符串 s 的一个切片,其中移除了 cutset 中包含的所有前导 Unicode 代码点
由于第一个参数(cutset)中有一个 'a',所以account中的前导 'a' 被移除了。
英文:
It is working as documented:
> TrimLeft returns a slice of the string s with all leading Unicode
> code points contained in cutset removed
Because there's an 'a' in the first argument (the cutset) the leading 'a' in account is removed
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论