Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: how to check if a string contains multiple substrings?

Tags:

string

go

strings.Contains(str_to_check, substr) takes only one argument as the substring to check, how do I check multiple substrings without using strings.Contains() repeatedly?

eg. strings.Contains(str_to_check, substr1, substr2)

like image 264
jm33_m0 Avatar asked Nov 06 '17 07:11

jm33_m0


People also ask

How to check if a string contains any of the substrings?

This post will discuss how to check if a string contains any of the substrings from a List. 1. Using String.contains () method The idea is to iterate over the entire list using an enhanced for loop and call the String.contains () method for each substring.

How do I iterate through a list of strings with substrings?

The idea is to iterate over the entire list using an enhanced for loop and call the String.contains () method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.

How to check if string contains two non-overlapping sub-strings without overlapping?

Given a string str, the task is to check whether the string contains two non-overlapping sub-strings s1 = “geek” and s2 = “keeg” such that s2 starts after s1 ends. given string without overlapping. “geek” and “keeg” both are present but they overlap.

How to check for a substring in a stream in Java?

Starting with Java 8, you can use Stream API for this task. The idea is to call the anyMatch () method on the stream elements, which return true if and only if any element matches with the supplied predicate. To check for a substring, you can use the contains () method.


2 Answers

You can write your own utility function using strings.Contains() that can work for multiple sub-strings.

Here's an example that returns Boolean (true/false) in case of complete / partial match and the total number of matches:

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 }

Here's the live example: https://play.golang.org/p/Xka0KfBrRD

like image 105
Azeem Avatar answered Oct 08 '22 01:10

Azeem


Yes, you can do this without calling strings.Contains() multiple times.

If you know substrings in advance the easiest way to check this with regular expression. And if a string to check is long and you have quite a few substrings it can be more fast then calling multiple strings.Contains

Example https://play.golang.org/p/7PokxbOOo7:

package main

import (
    "fmt"
    "regexp"
)

var re = regexp.MustCompile(`first|second|third`)

func main() {
    fmt.Println(re.MatchString("This is the first example"))
    fmt.Println(re.MatchString("This is the second example after first"))
    fmt.Println(re.MatchString("This is the third example"))
    fmt.Println(re.MatchString("This is the forth example"))
}

Output:

true
true
true
false

If the subs to check are dynamic it may be a bit more difficult to create regex as you need to escape special characters and regex compilation is not fast so strings.Contains() may be better in this case though it's better test if your code is performance critical.

Another good option could be to write your own scanner that can leverage common prefixes in substrings (if any) using prefix tree.

like image 20
Alexander Trakhimenok Avatar answered Oct 07 '22 23:10

Alexander Trakhimenok