-1
\$\begingroup\$

I have this find function. Is it concise, efficient and readable with good logic flow?

// findFirstStringInBracket finds the first string enclosed in brackets.
func findFirstStringInBracket(str string) string {
    if len(str) > 0 {
        indexFirstBracketFound := strings.Index(str, "(")
        if indexFirstBracketFound >= 0 {
            runes := []rune(str)
            wordsAfterFirstBracket := string(runes[indexFirstBracketFound:len(str)])
            indexClosingBracketFound := strings.Index(wordsAfterFirstBracket, ")")
            if indexClosingBracketFound >= 0 {
                runes := []rune(wordsAfterFirstBracket)
                return string(runes[1 : indexClosingBracketFound-1])
            } else {
                return ""
            }
        } else {
            return ""
        }
    } else {
        return ""
    }
    return ""
}
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Welcome to Code Review! We need to know what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the purpose of the code. We want to know why much more than how. The more you tell us about what your code is for, the easier it will be for reviewers to help you. The title needs an edit to simply state the task, rather than your concerns about the code. \$\endgroup\$ – Toby Speight Jan 20 at 13:12
0
\$\begingroup\$

You took something simple and made it complicated. Keep it simple and readable.

func findFirstStringInBrackets(s string) string {
    i := strings.IndexByte(s, '(')
    if i < 0 {
        return ""
    }
    i++
    j := strings.IndexByte(s[i:], ')')
    if j < 0 {
        return ""
    }
    return s[i : i+j]
}
\$\endgroup\$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.