💡 swift의 string 은 값 타입이다.
string이 다른 함수/메서드로부터 생성되어 string 값이 할당될 때, string의 레퍼런스를 할당하는 것이 아니라 값을 복사해서 생성한다.
즉, 다른 메소드에서 할당받은 문자열은 그 문자열을 수정해도 원본 문자열이 변하지 않는다는 것이다.
1. 기본 문자열
문자 배열을 이용해 문자열의 초기화 메서드에 인자로 넣어 문자열을 생성할 수 있다.
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"] //배열형
let catString = String(catCharacters) //문자열 초기화 메소드
print(catString)
// Print "Cat!🐱"
백슬래쉬 괄호를 이용해 상수, 변수, 리터럴 값을 문자열에 추가할 수 있다.
let mutiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
//"3 times 2.5 is 7.5"
여러 줄의 문자열을 사용하고 싶으면 큰 따옴표 3개(""")로 묶어서 사용할 수 있다. 여러 줄 문자열을 사용할 때는 첫 시작의 """ 다음 줄부터 마지막 """의 직전까지를 문자열로 본다. 여러줄을 통해 이루어진 문자열의 앞에 있는 whiteSpace는 생략된다.
let quotation =
"""
The White Rabbit put on his spectacles.
"Where shall i begin, please your Majesty?" he asked.
"Begin at the beginning," the King said gravely,
"and go on till you come to the end; then stop."
"""
let singleLine = "These are the same."
let multiLines = """These are the same."""
- 여러줄 문자열을 사용해 줄 바꿈을 하고 싶으면 백슬래쉬(\)를 사용한다.
let softWrappedQuotation =
"""
The White Rabbit put on his spectacles. "Where shall i begin, \
please your Majesty?" he asked.
"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""
//The White Rabbit put on his spectacles. "Where shall i begin, please your Majesty?" he asked.
//"Begin at the beginning," the King said gravely, "and go on till you come to the end; then stop."
- 문자열 시작과 끝에 각각 빈 줄을 넣고 싶다면 한 줄을 띄워서 문자열 입력
let lineBreaks = """
This string starts with a line break.
It also ends with a line break.
"""
//
//This string starts with a line break.
//It also ends with a line break.
//
- 들여쓰기 가능. 기준은 끝나는 지점의 """ 위치.
//"""위치 앞에 있는 문자들은 전부 무시되고 그 이후의 공백은 문자열에 반영
let linesWithIndentation = """
This line doesn't begin with whitespace.
This line begins with four spaces.
This line doesn't begin with whitespace.
"""
//This line doesn't begin with whitespace.
// This line begins with four spaces.
// This line doesn't begin with whitespace.
- 특수 문자
//특수문자
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
//"Imagination is more important than knowledge" - Einstein
let dollaSign = "\u{24}" // $, 유니코트 U+0024
let blackHeart = "\u{2665}" // ♥, 유니코드 U+2665
let sparklingHeart = "\u{1F496}" // 💖,유니코드 U+1F496
- 빈 문자열 초기화
var emptyString = ""
var anotherEmptyString = String()
2. String 접근
인덱스 접근(String [Int])으로 개별 문자에 접근하기 어렵기 때문에, 메서드를 사용해야 한다.
String.index 메소드를 통해, 개별 문자 혹은 범위로의 접근 가능 → startIndex, endIndex
//개별 character 접근
let str = "hello"
print(str.startIndex) //0
print(str.endIndex) //5
//문자열은 마지막에 '\0' 을 가지고 있기 때문에. -> 문자열 끝을 알기 위해
//endIndex는 4가 아닌 5
print(str[str.startIndex]) //'h\n'
print(str[str.index(after: str.startIndex)]) //'e\n'
print(str[str.index(before: str.endIndex)]) //'o\n'
print(str[str.endIndex]) //error: string index is out of bounds
print(str[1]) //error: cannot subscript String with an Int, use a String. Index instead.
- str.index(after: str.startIndex) : 시작 인덱스 다음 인덱스
- str.index(before: str.endIndex): 마지막인덱스 이전 인덱스
- str.endIndex 가 출력되지 않은 이유: endIndex는 마지막'\0'를 가리키고 있기 때문에
중간에 있는 문자에 접근하기 위한 index(_:offsetBy:) 메소드를 별도로 제공. → 시작 지점부터 떨어진 정수 값만큼을 더한 위치 반환
let str = "hello world"
print(str[str.index(str.startIndex, offsetBy: 0))]) //h
print(str[str.index(str.startIndex, offsetBy: 6))]) //w
print(str[str.index(str.endIndex, offsetBy: -1))]) //d
print(str[str.index(str.endIndex, offsetBy: -3))]) //r
//전체 길이에서 + offsetBy
loop를 통해 전체 string에 접근하기
: 문자열의 개별 문자를 for-in loop를 사용해 접근할 수 있다.
let str = "hello"
for s in str{
print(s)
}
//h
//e
//l
//l
//o
- indices를 사용해서 인덱스에 접근하는 방식
정수 인덱스가 아닌 swift에서 만들어낸 인덱스에 접근한다! index!= 정수.
for index in str.indices{
print(index)
print(str[index])
}
//Index(_rawBits: 1)
//h
//Index(_rawBits: 65793)
//e
//Index(_rawBits: 131329)
//l
//Index(_rawBits: 196865)
//l
//Index(_rawBits: 262401)
//o
- 인덱스와 개별 문자에 동시에 접근하는 방식 → index = 정수
for (index, value) in str.enumerated(){
print("index: \(index), value: \(value)")
}
//index: 0, value: h
//index: 1, value: e
//index: 2, value: l
//index: 3, value: l
//index: 4, value: o
3. String Insert, Remove
- Insert
let str = "Hello"
//insert(_:at:) insert(contentsOf:at:)
//contentsOf: 넣을 문자열, at: 넣을 위치
//개별 character을 삽입할 때, contentsOf를 사용하지 않아도 된다!!
str.insert("A", at:str.startIndex)
//AHello
str.insert(contentsOf: " World", at: str.endIndex)
//AHello World
- Remove
var str = "AHello World"
str.remove(at: str.startIndex)
//Hello World
let rangeOfWorld = str.index(str.endIndex, offsetBy: -6)..<str.endIndex
//문자열 길이: 11, offsetBy: -6 => 5
//범위: [5, 11) -> 5 ~ 10 (5, 6, 7, 8, 9, 10)
//index: 5부터 10까지의 범위 [substring]
//"Hello World" - " World" = "Hello"
str.removeSubrange(rangeOfWorld)
//Hello
[연습]
var greeting = "hello there"
var greeting1 = "hello there"
var greeting2 = "hello there"
//h e l l o " " t h e r e "\0"
//0 1 2 3 4 5 6 7 8 9 10 11
let range = greeting.index(greeting.endIndex, offsetBy: -6)..<greeting.endIndex
//range :5~10
greeting.removeSubrange(range)
//"hello"
let range1 = greeting1.startIndex..<greeting1.index(greeting1.startIndex, offsetBy: 6)
//range : 0~5
greeting1.removeSubrange(range1)
//"there"
let range2 = greeting2.startIndex...greeting2.index(greeting2.startIndex, offsetBy: 5)
//range : 0~5
greeting2.removeSubrange(range2)
//"there"
4. Prefix, Suffix(접두사, 접미사)
String의 앞쪽 혹은 뒤쪽에 찾고자 하는 문자가 있는지를 확인할 수 있도록 해주는 메서드.
특정 문자열이 앞(뒤)에서부터 포함되어 있는지 확인할 때 좋은 메소드
//hasPrefix()
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]
var act1SceneCount = 0
for scene in remeoAndJuliet {
if scene.hasPrefix("Act 1 ") { //접두사 "Act 1 "
act1SceneCount += 1
}
}
print("There are \(act1SceneCount) scenes in Act 1")
// There are 5 scenes in Act 1
//hasSuffix
var mansionCount = 0
var cellCount = 0
for scene in remeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") { //접미사 "Capulet's mansion"
mansionCount += 1
} else if scene.hasSuffix("Friar Lawrence's cell") {
cellCount += 1
}
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// 6 mansion scenes; 2 cell scenes
참고: https://jusung.gitbook.io/the-swift-language-guide/language-guide/03-strings-and-characters
'Swift' 카테고리의 다른 글
[Swift] DateFormatter 털어보기 (1/2) (0) | 2024.06.17 |
---|---|
[Swift] 고차 함수를 알아보자! (1) | 2023.11.25 |
Value Type vs Reference Type (1) | 2022.12.30 |
[Swift] 10진수 ↔ 2진수 변환하기 (0) | 2022.12.27 |
[Swift] 문자열과 문자(Strings & Characters) (2/2) (0) | 2022.02.13 |