Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

The Go library strings contain functions to handle the string operations. This time the function Contains could be used. The Contains function simply checks whether the string has a given substring. In fact, the function Index is used in Contains function.

To check whether the string begins with the substring, the HasPrefix function is there. To check whether the string ends with the substring, the function HasSuffix will work.

In fact, the Contains function is implemented by use of the Index function from the same package. As you can guess, the actual implementation works like this: if the index of the given substring is greater than -1, the Contains function returns true

The HasPrefix and HasSuffix functions work in a different way: the internal implementation just checks the length of both the string and substring, and if they are equal or the string is longer, the required part of the string is compared.