How to check if String contains a Substring in Go?
How to check if String contains a Substring in Go?
Go ? Check if String contains a Substring
To check if string contains a substring in Go, call Contains function of strings package and provide the string and substring as arguments to the function.
Contains function returns a boolean value. It returns true if the substring is present in the string, or false if not.
The definition of Contains function in strings package is
func Contains(s, substr string) bool
The syntax to check if string substr is present in the string str is
strings.Contains(str, substr)
Examples
In the following example, we check if string substr is present in the string str using Contains function.
example.go
package main import (
"fmt" "strings" ) func main() { str := "abcdefgh" substr := "cd" if strings.Contains(str, substr) {
fmt.Println("The substring is present in the string.") } else {
fmt.Println("The substring is not present in the string.")
fmt.Println("The substring is not present in the string.") } }
Output
The substring is present in the string.
Now, let us take values in str and substr such that substr is not present in str , and check this programmatically using Contains function.
example.go
package main import (
"fmt" "strings" ) func main() { str := "abcdefgh" substr := "xy" if strings.Contains(str, substr) {
fmt.Println("The substring is present in the string.") } else {
fmt.Println("The substring is not present in the string.") } }
Output
The substring is not present in the string.
Conclusion
In this Golang Tutorial, we learned how to check if a substring is present in a string in Go programming language, with the help of example programs.
Golang Golang Tutorial Run Golang Program Golang If Else Golang Switch
Golang For Loop Golang Comments Golang Functions Golang Array Golang Slice Golang Struct Golang Class Golang Range Golang Map Golang Goroutine Golang Channel
Golang String Operations Golang String Length Golang String Concatenation Golang Split String Golang String - Get Index of Substr Golang String to Uppercase Golang String to Lowercase Golang Convert String to Integer
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- python check if dictionary contains key
- check if array contains javascript
- check if array contains java
- check if array contains element java
- powershell check if array contains string
- how to check if ram is running
- javascript check if string is in array
- powershell check if string contains substring
- powershell check if string contains text
- check if string contains powershell script
- powershell check if string contains character
- how to sum if cell contains text