package main
import (
"fmt"
"strings"
)
func replaceNestedBraces(s1, target, replacement string) string {
for {
start := strings.Index(s1, target)
if start == -1 {
break
}
// 找到嵌套的结束位置
end := start + len(target)
depth := 1
for ; end < len(s1); end++ {
if s1[end] == '{' {
depth++
} else if s1[end] == '}' {
depth--
if depth == 0 {
break
}
}
}
if depth == 0 {
newPart := s1[:start] + replacement + s1[end+1:]
s1 = newPart
}
}
return s1
}
代码使用示例
func main() {
s1 := "I like {fruit}, { { {fruit} } } is delicious."
target := "{fruit}"
replacement := "apple"
result := replaceNestedBraces(s1, target, replacement)
fmt.Println(result)
}
使用的字符串处理函数及思路
- strings.Index:用于查找目标子字符串
target
在字符串 s1
中的起始位置。如果找不到,返回 -1。
- 遍历查找嵌套结束位置:找到起始位置后,通过遍历字符串,使用一个变量
depth
记录花括号的嵌套深度,找到匹配的结束花括号位置,确保替换的是完整的嵌套部分。
- 字符串拼接替换:根据找到的起始和结束位置,将原字符串分成三部分,中间替换为目标字符串,再拼接起来,更新原字符串
s1
。
- 循环替换:使用
for
循环不断查找并替换,直到字符串中不再存在目标子字符串为止。最终返回替换后的字符串。