How to check if a string contains a substring in Golang?
Checking if a string contains a substring is one of the most common tasks in any programming language. A substring is a contiguous sequence of characters within a string. For example, "bc" is a substring of "abcd".
Golang offers many ways to check if a string contains a substring. Use strings.Contains function to check if string contains substring, it returns True if substring present in given string.
Substring Example with boolean output
// Golang program to illustrate
// the strings.Contains() Function
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Contains("abcd", "bc")) // true
fmt.Println(strings.Contains("abcd", "cb")) // false
}
This strings.Contains returns true if the string contains the substring, otherwise, it returns false. strings.Contains takes two arguments, one on the left and one on the right, and returns True if the right argument string is contained within the left argument string.
Substring example to print the desired result instead of a boolean output
package main
import (
"fmt"
"strings"
)
func main() {
input := "iPhone"
str := "Why Apple is the best place to buy iPhone."
if strings.Contains(str, input) {
fmt.Println("Yes")
}
}
Most Helpful This Week
How to check if a string contains certain characters in Golang?
How to check string contains uppercase lowercase character in Golang?
How to check lowercase characters in a string in Golang?
How to check if a string contains only letters in Golang?
How to check if a string contains a numbers in Golang?
How to check UPPERCASE characters in a string in Golang?