Golang : Check if a string contains multiple sub-strings in []string?
Problem :
You have a string and you use strings.Contains()
function to determine if there is a sub-string inside the main string.
Such as :
Main string : ["apple is fruit"]
Sub string : ["apple"]
Now, you want to check against multiple sub-strings instead of just a single sub-string.
Main string : ["apple is fruit and tomato is a vegetable"]
Sub strings : ["fruit", "apple", "orange"]
How to do that?
Solution :
I've developed a bad word language filter for my own use. The has()
function below used the strings.Index()
function to determine if a bad word is inside the main string and break the for loop at first instance of a bad word detected. You can modified it for your own use. Perhaps, append those bad words into a slice and report them instead of breaking the for loop at first instance.
func has(input string, words []string) (bool, string) {
for _, word := range words {
if strings.Index(input, word) > -1 {
return true, word
break
}
}
return false, ""
}
var badWords = []string{"fuck", "shit", "cunt"}
result, badWordFound := has(input, badWords)
if result {
fmt.Println("The word %s is a bad word.\n", badWordFound)
}
Is there another way to do this? Sure! You can use the strings.ContainsAny()
function too.
Here you go!
package main
import (
"fmt"
"strings"
)
func main() {
x := "I feel like having a good sleep tonight"
y := []string{"like", "having"}
for i := 0; i < len(y); i++ {
//fmt.Println(strings.ContainsAny(x,y[i]))
if strings.ContainsAny(x, y[i]) {
fmt.Printf("Detected word - [%s]\n", y[i])
}
}
}
Play at : http://play.golang.org/p/CSVQprocj4
Happy coding!
Reference :
https://www.socketloop.com/tutorials/golang-how-to-check-if-a-string-contains-another-sub-string
See also : Golang : How to check if a string contains another sub-string?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Tutorials
+7.3k Golang : Mapping Iban to Dunging alphabets
+9.2k Golang : Extract or copy items from map based on value
+15.2k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+15.2k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+5.1k Unix/Linux : How to archive and compress entire directory ?
+34.7k Golang : Upload and download file to/from AWS S3
+13.1k Golang : Get constant name from value
+6.9k Golang : Gorrila mux.Vars() function example
+39.6k Golang : Convert to io.ReadSeeker type
+9.8k Golang : Bcrypting password
+13.6k Golang : convert rune to unicode hexadecimal value and back to rune character
+16.6k Golang : How to generate QR codes?