String trim in the golang
I found it somewhat confusing at first sight and done lots of buggy code due to the misunderstanding of the trim functions.
func TrimLeft(s string, cutset string) string
as shown in the trimleft function it takes two arguments
- Input string
- cutset string
Here cutset string is not the string it means the string made of the runes you want to trim from left side until a rune found that is not defined in the cutset string
cutted_string := trimleft ( "hello manish","he") fmt.println(cutted_string )
It will give output string as
Now lets edit the cutset string,
cutted_string := trimleft ( "hello manish","hel")
If you are like me you might be expecting this output
But its exctual ouput is "o manish"
The reason is trim left trims the runes ( characters ) from left side until a rune found that is not inside the cutset list.
If you want to trim the string/word "hello" either you have to use TrimPrefix or Use Replace
cutted_string := trimPrefix ( "hello manish","hello")
it will give output string as
See this golang playground example,
If you want to actually trim the word or string from the parent string instead of using the trimLeft or trimRight use trimSuffix or trimPrefix and if the word/string occurs in between the string use Replace function.