Go 语言如何实现多行文本统一缩进?
是的,Go 语言可以使用 strings.Replace() 函数实现传入的多行文本统一缩进 6 个字符。
下面是一个示例代码:
package main
import (
"fmt"
"strings"
)
func indentText(text string, indentSize int) string {
indent := strings.Repeat(" ", indentSize)
return indent + strings.Replace(text, "\n", "\n" + indent, -1)
}
func main() {
text := `Hello
World
This is a test`
indentedText := indentText(text, 6)
fmt.Println(indentedText)
}
输出结果为:
Hello
World
This is a test
在上面的示例中,indentText() 函数接受两个参数:text 表示要缩进的文本,indentSize 表示缩进的字符数。indent 变量用于生成指定数量的空格字符。然后,使用 strings.Replace() 函数将换行符替换为换行符加缩进字符,从而实现缩进的效果。
原文地址: https://www.cveoy.top/t/topic/piuj 著作权归作者所有。请勿转载和采集!