Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

Code Habit

Golang ) 문자열 파싱하기 본문

카테고리 없음

Golang ) 문자열 파싱하기

코드베어 2020. 6. 16. 07:53

golang에서는 다양한 문자열 관련 함수들을 제공한다. 그 중 문자열 파싱할 때 자주 사용하는 몇 가지 함수들만 알아보겠다.

 

  • func Contains(s, substr string) bool : s 안에 substr 이 포함되어 있는지 검사 -> true : 포함, false :  불포함
  • func ContainsAny(s, chars string) bool : s 안에 chars의 문자가 포함되어 있는지 검사 -> true : 포함, false : 불포함
  • func Count(s, substr string) int : s안에 substr문자열이 몇번 나오는지 검사 -> 개수 리턴
  • func Index(s, substr string) int : s안에 substr 의 위치를 구함(첫글자). 리턴값이 -1이면 불포함

예제 )

package main
 
import (
    "fmt"
    "strings"
)
 
func main() {
    s := "one two two three three three four 4"
 
    b := strings.Contains(s, "one")
    fmt.Println(b) // true
 
    b = strings.Contains(s, "five")
    fmt.Println(b) // false
 
    b = strings.ContainsAny(s, "oa"// 'o' 포함
   fmt.Println(b) // true
 
    b = strings.ContainsAny(s, "abc")
    fmt.Println(b) // false
 
    n := strings.Count(s, "three")
    fmt.Println(n) // 3
 
    n = strings.Count(s, "five")
    fmt.Println(n) // 0
 
    n = strings.Index(s, "two")
    fmt.Println(n) // 4
 
    n = strings.Index(s, "five")
    fmt.Println(n) // -1
}