Go 문자열에서 특정 문자열부터 특정 문자열까지의 부분문자열을 다른 문자열로 교체하기

Jmnote (토론 | 기여)님의 2024년 8월 22일 (목) 14:07 판 (→‎개요)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

개요[ | ]

Go 문자열 부분문자열 교체하기
Go 문자열에서 시작 문자열부터 끝 문자열까지의 부분문자열을 다른 문자열로 교체하기
Go 문자열에서 특정 문자열부터 특정 문자열까지의 부분문자열을 다른 문자열로 교체하기
import (
	"fmt"
	"strings"
)

func replaceSubstring(str, start, end, replacement string) string {
	startIndex := strings.Index(str, start)
	if startIndex == -1 {
		return str
	}

	endIndex := strings.Index(str[startIndex+len(start):], end)
	if endIndex == -1 {
		return str
	}

	substring := str[startIndex+len(start):startIndex+len(start)+endIndex]
	replacedString := strings.Replace(str, substring, replacement, 1)
	return replacedString
}

func main() {
	str := "This is a test string."
	start := "is"
	end := "string"
	replacement := "example"

	replacedString := replaceSubstring(str, start, end, replacement)
	fmt.Println(replacedString) // Output: This is a example.
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}