strings 패키지는 문자열을 다루는 함수를 제공해요.
아래는 이 패키지에 있는 함수 중 일부예요. 나머지 함수는 문서에서 확인해 봐요!
| 역할 | 함수 | 설명 |
|---|---|---|
| 대소문자 변환 | ToLower | 문자열을 소문자로 변환해요 |
| 대소문자 변환 | ToUpper | 문자열을 대문자로 변환해요 |
| 검색 | Contains | 문자열에 특정 부분 문자열이 포함되어 있는지 확인해요 |
| 검색 | Count | 겹치지 않는 부분 문자열의 등장 횟수를 세요 |
| 검색 | HasPrefix | 문자열이 특정 부분 문자열로 시작하는지 확인해요 |
| 검색 | HasSuffix | 문자열이 특정 부분 문자열로 끝나는지 확인해요 |
| 검색 | Index | 부분 문자열이 처음 등장하는 인덱스를 반환하고, 없으면 -1을 반환해요 |
| 수정 | Replace | 부분 문자열을 최대 n번 바꿔요 |
| 수정 | ReplaceAll | 부분 문자열을 모두 바꿔요 |
| 수정 | TrimSpace | 앞뒤의 공백을 제거해요 |
| 분할 및 결합 | Fields | 공백을 기준으로 문자열을 단어로 나눠요 |
| 분할 및 결합 | FieldsSeq | 단어를 하나씩 가져와요 |
| 분할 및 결합 | Join | 문자열 슬라이스를 구분자로 결합해요 |
| 분할 및 결합 | Split | 구분자를 기준으로 문자열을 여러 부분으로 나눠요 |
| 분할 및 결합 | SplitSeq | 각 부분을 하나씩 가져와요 |
import (
"fmt"
"strings"
)
// Case conversion
strings.ToLower("Gopher") // "gopher"
strings.ToUpper("Gopher") // "GOPHER"
// Searching
strings.Contains("Apple", "le") // true
strings.Index("Apple", "le") // 3
strings.Index("Apple", "xyz") // -1
strings.Count("test", "t") // 2
strings.HasPrefix("Gopher", "Go") // true
strings.HasSuffix("Gopher", "er") // true
// Modifying
strings.TrimSpace(" hello ") // "hello"
strings.Replace("aabbcc", "b", "x", 1) // "aaxbcc"
strings.ReplaceAll("aabbcc", "b", "x") // "aaxxcc"
// Splitting or Joining
strings.Fields(" a b\tc ") // []string{"a", "b", "c"}
strings.Split("a,b,c", ",") // []string{"a", "b", "c"}
strings.Join([]string{"a", "b", "c"}, ",") // "a,b,c"
// You do not need to worry about this range syntax yet.
// It is covered later in the range iteration concept.
for word := range strings.FieldsSeq(" a b\tc ") {
fmt.Println(word)
}
// Output:
// a
// b
// c
for part := range strings.SplitSeq("a,b,c", ",") {
fmt.Println(part)
}
// Output:
// a
// b
// c