How to search a letter in a string with Golang?

Asked

Viewed 303 times

0

I need to take a user string and check if 1) The first letter begins with i or I 2) The last letter ends with n or N 3) If string theme letter a or A in the middle.

I started writing something like this, and I used the string package but the program keeps giving error

func main() {
    var s string
    fmt.Println("Type a word")
    fmt.Scan(&s)
    //procurar na string
    verificaA := strings.Contains(s, "A")
    verificaa := strings.Contains(s, "a")
    num := len(s)

    if s[0] == 'i' || s[0] == 'I' {
        if s[num-1] == 'n' || s[num-1] == 'N' {
            if verificaA == true || verificaa == true {
                fmt.Println("Found!")
            }
        }
    } else {
        fmt.Println("Not Found!")
    }
}
go

1 answer

4


I don’t know where you intend to use this code, but an alternative solution would be the use of regular expressions.

package main

import (
    "fmt"
    "os"
    "regexp"
)

func main() {
    s := "IiiiIiII    a   A    NnNnN"
    matched, err := regexp.MatchString(`^(?i)i.*a.*n$`, s)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Printf("found: %v\n", matched)
}

https://play.golang.org/p/da2Og7NIwz8

PS: If you are going to use this code in a "tight loop", you better compile the regular expression with regexp.MustCompile for more performance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.