[英]How to insert a string inside another string using Go lang
Most programming languages have a function that allows us to insert one string into another string.大多数编程语言都有一个函数,允许我们将一个字符串插入另一个字符串。 For example, I can take the string Green and the string HI, and perform an operation Green.insert(HI,2) to get the resulatant string GrHIeen.例如,我可以获取字符串 Green 和字符串 HI,并执行 Green.insert(HI,2) 操作以获取结果字符串 GrHIeen。 But such a function does not come with the standard GO lang library.但是标准的 GO 语言库没有这样的功能。
Is there any Golang function which I can use to insert a string inside an string?是否有任何 Golang 函数可用于在字符串中插入字符串?
For example例如
string = "</table></body></html>"
// I want Following Output
string = "</table><pagebreak /></body></html>"
You can simply use slice operations on the string:您可以简单地对字符串使用切片操作:
package main包主
func main() {
p := "green"
index := 2
q := p[:index] + "HI" + p[index:]
fmt.Println(p, q)
}
Working example: https://play.golang.org/p/01phuBKuBB工作示例:https: //play.golang.org/p/01phuBKuBB
You could turn the first string into a template for Sprintf.您可以将第一个字符串变成 Sprintf 的模板。 It would look like this:它看起来像这样:
p := "</table>%s</body></html>"
out := fmt.Sprintf(p,"<pagebreak />")
Working code here: https://play.golang.org/p/AInfyQwpy2此处的工作代码:https: //play.golang.org/p/AInfyQwpy2
I had used rune
and bytes.Buffer
to insert <\b>
bold tags at between two indexes and build a result string as below.我曾使用rune
和bytes.Buffer
在两个索引之间插入<\b>
粗体标签并构建如下结果字符串。
for j:=0; j< len(resultstrIntervals);j++{
startIndex:= resultstrIntervals[j].Start
endIndex:= resultstrIntervals[j].End
for i <= endIndex && i <= len(s) {
if i == startIndex{
buffer.WriteRune('<')
buffer.WriteRune('b')
buffer.WriteRune('>')
}else if i == endIndex{
buffer.WriteRune('<')
buffer.WriteRune('/')
buffer.WriteRune('b')
buffer.WriteRune('>')
}
if i < len(strArr){
buffer.WriteRune(strArr[i])
}
i++
}
}
fmt.Print(buffer.String())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.