How to skip values ​​in slice if condition is matched first time

王林
Release: 2024-02-08 21:15:21
forward
1151 people have browsed it

How to skip values ​​in slice if condition is matched first time

php editor Banana will introduce to you how to skip the value of the first matching condition in the slice. During development, we often need to deal with slices of arrays or strings, but sometimes we want to skip the first value in the slice that meets a specific condition. This may be because we only care about subsequent matches, or we only need to process values ​​after a specific position. Next, we'll explore several solutions to help you achieve this goal.

Question content

How to skip values ​​in a slice if the condition matches once.

func main() {

    cloud := []string{"moon", "earth", "moon-light"}

    for _, value := range cloud {

        if strings.Contains(value, "mo") {
            fmt.Println("print1")
        } else if strings.Contains(value, "ear") {
            fmt.Println("print2")
        }
    }
}
Copy after login

Output: print 1 Print 2 Print 1

Expected output: print 1 Print 2

Thanks!

Solution

You can use the map to find out if a specific situation occurs. It's better than using variables because it allows you to track a large number of conditions without causing any confusion. Here is an example of what you want:

cloud := []string{"moon", "earth", "moon-light"}
var conditionTracker = make(map[string]bool)

for _, value := range cloud {

    if _, ok := conditionTracker["first_condition"]; !ok && strings.Contains(value, "mo") {
        conditionTracker["first_condition"] = true
        fmt.Println("print1")
    } else if _, ok := conditionTracker["second_condition"]; !ok && strings.Contains(value, "ear") {
        conditionTracker["second_condition"] = true
        fmt.Println("print2")
    }
}
Copy after login

The above is the detailed content of How to skip values ​​in slice if condition is matched first time. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!