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 " "
} else {
result = result string(inputString[index])
}
}
return result
}
for example for inputString = Mr Smith
and inputLength = 10
the result
is Mr SmithXX
. 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.
CodePudding user response:
DO NOT PANIC!
inputString =
Mr Smith
and inputLength =10
the result isMr SmithXX
. 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, " "...)
} else {
t = append(t, b)
}
}
for i := tLen - len(s); i > 0; i-- {
t = append(t, 'X')
}
return string(t)
}
func main() {
s := "Mr Smith"
tLen := 10
fmt.Println(s, tLen)
t := transform(s, tLen)
fmt.Println(t)
}
https://go.dev/play/p/SKwD_5yPa6C
Mr Smith 10
Mr SmithXX