string.Contains Function in Golang with Examples

string.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false.

Syntax:

func Contains(str, substr string) bool

Here, str is the original string and substr is the string which you want to check. Let us discuss this concept with the help of an example:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// the strings.Contains() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    // using the function
    fmt.Println(strings.Contains("GeeksforGeeks", "for"))
    fmt.Println(strings.Contains("A computer science portal", "science"))
  
}

chevron_right


Output:



true
true

Explanation: In the above example, we check the presence of sub-string ‘for’ and ‘science’ in different strings. Since strings.Contains() function returns boolean value, it returns true in both the cases.

Example 2: Following example illustrates how the user can print the desired result instead of a boolean output:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// the strings.Contains() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
    input := "Golang"
  
    str := "This is a Golang program"
  
    if strings.Contains(str, input) {
        fmt.Println("Yes")
    }
}

chevron_right


Output:

Yes

Explanation: In the above example, we take a sub-string as ‘input’ and the main string as ‘str’. Then, we check if ‘Golang’ is present in the main string. If so, ‘Yes’ is returned as the output as shown above.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.