1. Substring
String의 일부를 지칭하는데, 아래와 같이 두 개의 string이 있을 때 str은 str2에 포함된 패턴으로 일종의 substring이라고 생각할 수 있다. 하지만 둘은 서로 다른 메모리를 사용하기 때문에 메모리 측면에서는 다른, 서로 포함 관계가 아니다.
let str = "Hello"
let str2 = "Hello World"
subStr은 새로운 메모리를 해당 변수에 할당하지 않고, 기존의 str 변수의 메모리를 재사용한다.
→ 메모리 재사용은 메모리 할당 비용을 줄여준다.
하지만, 장기적으로 string을 저장하는 경우에 적합하지 않으므로 장기로 string을 사용하면 새로운 string을 만들자.
let str = "Hello World"
let range = str[str.startIndex**...**str.index(str.startIndex, offsetBy: 4)]
let subStr = str[range] //Hello
부분 문자를 얻기 위해 prefix(_:)와 같은 서브 스크립트 메서드를 이용할 수 있는데, 이렇게 얻은 부분 문자열은 문자열 인스턴스가 아니라 부분 문자열 인스턴스이다. 만약 오래 사용한다면 문자열 인스턴스로 바꿔서 사용하는 것이 좋다.
→ 메모리 관리 때문인데, SubString은 해당 문자를 직접 갖고 있는 것이 아니라 원본 String의 메모리를 참조해 사용한다. 그래서, SubString을 계속 이용하면 원본 String이 계속 메모리에 남아있게 된다. 즉, 사용하지 않는 문자열까지도 남게 된다는 것이다.
let greeting = "Hello, world!"
let index = greeting.index(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
//beginning : Hello
//substring인 beginning을 string으로 변환
let newString = String(beginning)
2. 문자열을 배열로: String To Array
✨ map( ) : 문자열을 문자 하나하나로 쪼개서 배열로 만드는 방법
let str = "aBcDeF"
//Character 형을 요소로 갖는 배열
let charArr = str.map{$0}
print("\(charArr) : \(type(of: charArr))")
//"["a", "B", "c", "D", "e", "F"] : Array<Character>\n"
//String형을 요소로 갖는 배열
let strArr = str.map{String($0)}
print("\(strArr) : \(type(of: strArr))")
//"["a", "B", "c", "D", "e", "F"] : Array<String>\n"
3. 배열을 문자열로: Array To String
배열의 joined() 나 reduce()를 사용한다.
let array = ["A", "B", "C"]
let str1 = String(array);
//error
let str2 = array.joined(separator: "")
//"ABC"
let str3 = array.reduce("", +)
//"ABC"
4. 대소문자 변환
uppercased(), lowercased()를 사용.
기존 문자열을 변경하는 것이 아니라 새로운 문자열을 생성해 리턴.
let str = "hello swift127"
print(str.uppercased())
print(str.lowercased())
//HELLO SWIFT127
//hello swift127
💡공부 및 기록용 블로그이므로 오류가 있을 수 있습니다.💡
만약 문제에 오류나 오타가 있다면 댓글로 알려주세요➿
언제나 환영합니다. 감사합니다. 화이팅!
참고: 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) (1/2) (0) | 2022.02.13 |