본문 바로가기

카테고리 없음

Go언어 문자열 찾아 바꾸기

Go언어 문자열 단어 찾아서 바꾸기 go언어 문자열 바꾸기 단어 바꾸기 치환 교체 


golang 문자열 중에서 특정 단어를 찾고 그 단어를 다른 단어로 교체 하는 방법입니다.


우선 "strings" 를 import 합니다.


package main

import (
    "fmt"
    "strings"
)


그다음 strings.Replace 함수를 이용합니다.


strings.Replace 함수의 파라미터는 ( "문자열", "찾고 싶은 문자열", "바꾸고 싶은 문자열", -1)

와 같이 사용합니다. 

book 문자열에서 apple을 banana로 바꾸려면 strings.Replace(book, "apple", "banana", -1) 과 같이 수행합니다.

맨 뒤의 -1 옵션은 모든 단어를 찾아 바꾸는 옵션입니다. 2로 하면 2개만 바꿉니다.

   

func main() { book := "apple is better than kiwi" // Replace the "apple" with "banana" result := strings.Replace(book, "apple", "banana", -1) fmt.Println(result) }

결과: apple is better than kiwi

banana is better than wiki