How to check if each letter in a string maps to the first letter of a word in another string with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
    "unicode"
)

func matchesPattern(pattern, sentence string) bool {
    words := strings.Fields(sentence)

    // Length mismatch → automatic failure
    if len(pattern) != len(words) {
        return false
    }

    // Compare each pattern character to the first letter of each word
    for i, w := range words {
        p := unicode.ToLower(rune(pattern[i]))
        first := unicode.ToLower(rune(w[0]))

        if p != first {
            return false
        }
    }

    return true
}

func main() {
    pattern := "jpcrg"
    sentence := "java python c rust go"

    if matchesPattern(pattern, sentence) {
        fmt.Println("Pattern matches!")
    } else {
        fmt.Println("Pattern does NOT match.")
    }
}




/*
run:

Pattern matches!

*/

 



answered Jan 6 by avibootz

Related questions

...