Last active
May 22, 2019 07:11
-
-
Save iamazeem/9fb7a7bdf789b2d0c5c6b18596ab3ad4 to your computer and use it in GitHub Desktop.
Go: Check multiple substrings in string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "strings" | |
| ) | |
| func checkSubstrings(str string, subs ...string) (bool, int) { | |
| matches := 0 | |
| isCompleteMatch := true | |
| fmt.Printf("String: \"%s\", Substrings: %s\n", str, subs) | |
| for _, sub := range subs { | |
| if strings.Contains(str, sub) { | |
| matches += 1 | |
| } else { | |
| isCompleteMatch = false | |
| } | |
| } | |
| return isCompleteMatch, matches | |
| } | |
| func main() { | |
| isCompleteMatch1, matches1 := checkSubstrings("Hello abc, xyz, abc", "abc", "xyz") | |
| fmt.Printf("Test 1: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch1, matches1) | |
| fmt.Println() | |
| isCompleteMatch2, matches2 := checkSubstrings("Hello abc, abc", "abc", "xyz") | |
| fmt.Printf("Test 2: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch2, matches2) | |
| } | |
| // OUTPUT: | |
| // String: "Hello abc, xyz, abc", Substrings: [abc xyz] | |
| // Test 1: { isCompleteMatch: true, Matches: 2 } | |
| // String: "Hello abc, abc", Substrings: [abc xyz] | |
| // Test 2: { isCompleteMatch: false, Matches: 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment