"Go 문자열에서 특정 문자열부터 특정 문자열까지의 부분문자열을 다른 문자열로 교체하기"의 두 판 사이의 차이

(새 문서: ==개요== ;Go 문자열 부분문자열 교체하기 ;Go 문자열에서 시작 문자열부터 끝 문자열까지의 부분문자열을 다른 문자열로 교체하기 ;Go 문자...)
 
9번째 줄: 9번째 줄:
"strings"
"strings"
)
)


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


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


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

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 }}