[go] 문자열에서 특정 위치의 문자열 변경

Go 언어에서 문자열에서 특정 위치의 문자열을 변경하는 방법을 살펴보겠습니다.

방법 1: 문자열 슬라이싱을 사용하여 변경하기

문자열을 변경하기 위해서는 다음과 같이 슬라이싱을 사용할 수 있습니다.

package main

import (
    "fmt"
)

func main() {
    str := "Hello, World!"
    newStr := str[:5] + "Go" + str[5+len("Go"):]

    fmt.Println(newStr)  // 출력: HelloGo, World!
}

위 예제에서는 “Go” 문자열로 “Hello” 다음의 공백을 덮어썼습니다.

방법 2: strings 패키지의 Replace 함수 사용

또 다른 방법은 strings 패키지의 Replace 함수를 사용하여 원래 문자열에서 특정 문자열을 변경하는 것입니다.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello, World!"
    newStr := strings.Replace(str, "Hello", "Hi", 1)

    fmt.Println(newStr)  // 출력: Hi, World!
}

위의 예제에서는 “Hello”를 “Hi”로 바꾸기 위해 Replace 함수를 사용했습니다.

이제 Go 언어에서 문자열의 특정 위치에서 문자열을 변경하는 방법을 쉽게 알 수 있습니다.

더 자세한 정보는 Strings 패키지 문서를 참고하시기 바랍니다.