Search code examples
stringgoreplacetrim

Detecting a specific character string


Recently, I had a school project that made me struggle for a week. I really need help.

My program takes a string input and modifies it to return another string in its upper or lower case version, so far it works. But when I put in : "This is so exciting (up, 2)" the output stays the same when it should be "This is SO EXCITING" My point is to be able to handle the case : (up, n), knowing that the word followed by "(up)" must be capitalized. If below you will find the concerned function.

Thanks in advance !

// modifyUp converts words before (up) to uppercase
func modifyUp(line string) string {
    words := strings.Fields(line)
    var numWords int
    var numbers int

    for i, word := range words {
        if strings.HasSuffix(word, "(up)") && i > 0 {
            // Convert word(s) to uppercase
            numWords = 1
            if strings.Contains(word, ",") {
                // Handle comma-separated words
                numbers, _ = strconv.Atoi(strings.TrimSuffix(strings.Split(word, ",")[1], ")"))
                word = strings.TrimSuffix(word, fmt.Sprintf(",%d)", numbers))
                numWords += numbers
            } else {
                word = strings.TrimSuffix(word, "(up)")
            }
            // Convert preceding word(s) to uppercase
            for j := i - numWords + 1; j <= i; j++ {
                if j >= 0 {
                    words[j] = strings.ToUpper(words[j])
                }
            }
            // Replace modified word with original word
            words[i-numWords+1] = word
        }
    }
    return strings.Join(words, " ")

Solution

  • I finally found another way

    func modifyUp(line string) string {
        words := strings.Fields(line)
        //var numWords int
        var numbers int
    
        for i, word := range words {
            if word == "(up," && i < len(words)-1 {
                ok := splitWord(words[i+1])
                if ok {
                    wr := words[i+1]
                    numbers, _ = strconv.Atoi(wr[:len(wr)-1])
                    words[i], words[i+1] = "", ""
                    for j := i - 1; j >= 0; j-- {
                        if numbers == 0 {
                            break
                        } else {
                            words[j] = strings.ToUpper(words[j])
                            numbers--
                        }
                    }
                }
                break
            }
            if word == "(up)" && i > 0 {
                words[i-1] = strings.ToUpper(words[i-1])
                words[i] = ""
            }
        }
    
        return strings.Join(words, " ")
    }
    

    Thank all you for contibutions