Please help me write a function that takes input of a string and a number and outputs a shortened string to the number + "...". If the string does not exceed the size (number), then just output this string, but without the "...". Also, our string uses only single-byte characters and the number is strictly greater than zero.
My two attempts:
package main
import (
"fmt"
)
func main() {
var text string
var width int
fmt.Scanf("%s %d",&text,&width)
res := text[:width]
fmt.Println(res+"...")
}
But this function adds "..." even if the string does not exceed the width.
package main
import (
"fmt"
)
var text string
var width int
fmt.Scanf("%s %d",&text,&width)
if width <= 0 {
fmt.Println("")
}
res := ""
count := 0
for _, char := range text {
res += string(char)
count++
if count >= width {
break
}
}
fmt.Println(res+"...")
}
This function works the same way.