0

I'd like to catch panic: runtime error: index out of range in the following loop (inside function without returning) and concat X for each panic: runtime error: index out of range to the result:

func transform(inputString string, inputLength int) string {
    var result = ""
    for index := 0; index < inputLength; index++ {
        if string(inputString[index]) == " " {
            result = result + "%20"
        } else {
            result = result + string(inputString[index])
        }
    }
    return result
}

for example for inputString = Mr Smith and inputLength = 10 the result is Mr%20SmithXX. It has two X because 10 - 8 = 2.

I know I can catch the panic in returning from transform() but I'd like to handle it inside the loop without returning the function.

2
  • 1
    you can determine the length of inputString as a []rune or whatever, so why have length provided externally? Commented Oct 21, 2022 at 23:46
  • Handle it by checking the length of the slice. Commented Oct 22, 2022 at 0:01

1 Answer 1

0

inputString = Mr Smith and inputLength = 10 the result is Mr%20SmithXX. It has two X because 10 - 8 = 2.


package main

import "fmt"

func transform(s string, tLen int) string {
    t := make([]byte, 0, 2*tLen)
    for _, b := range []byte(s) {
        if b == ' ' {
            t = append(t, "%20"...)
        } else {
            t = append(t, b)
        }
    }
    for x := tLen - len(s); x > 0; x-- {
        t = append(t, 'X')
    }
    return string(t)
}

func main() {
    s := "Mr Smith"
    tLen := 10
    fmt.Printf("%q %d\n", s, tLen)
    t := transform(s, tLen)
    fmt.Printf("%q\n", t)
}

https://go.dev/play/p/wg7MIO8yUzF

"Mr Smith" 10
"Mr%20SmithXX"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.