I found it somewhat confusing at first sight and done lots of buggy code due to the misunderstanding of the trim functions.
TrimLeft
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
For example,
cutted_string := trimleft ( "hello manish","he") fmt.println(cutted_string )
It will give output string as
"llo manish"
Now lets edit the cutset string,
cutted_string := trimleft ( "hello manish","hel")
fmt.println(cutted_string )
If you are like me you might be expecting this output
"lo manish"
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
TrimPrefix
cutted_string := trimPrefix ( "hello manish","hello")
fmt.println(cutted_string )
it will give output string as
" manish"
See this golang playground example,
So ,
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.
Comments
Post a Comment