[Swift] 3. String & Characters

도윤·2021년 7월 12일
0

Swift

목록 보기
3/21

Strings and Characters

String Literals

미리 정의된 String 값으로 문자열 사용. " "안에 문자열을 써주면 된다.


let someString = "Some string literal value"

Multiline String Literals

여러 문자열을 사용하려면 """을 통해 사용.

"""안에서는 명령어 없이 줄바꿈이 일어나지 않는데, 줄바꿈을 하기 위해선 \을 사용하면 된다.


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."
"""

Special Characters in String Literals

\0 (null character),
\ (backslash),
\t (horizontal tab),
\n (line feed),
\r (carriage return),
\" (double quotation mark)
\' (single quotation mark)’

유니코드를 사용하려면 \u{n}을 쓰면 되고 1~8자리의 16진수를 쓰면 된다.


let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\u{24}"        // $,  Unicode scalar U+0024
let blackHeart = "\u{2665}"      // ♥,  Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // 💖, Unicode scalar U+1F496

"""를 사용하여 여러 문자를 쓸 경우엔 "는 그냥 사용 가능하지만 """을 사용하고자 한다면 \"""이나 \"\"\"를 사용하면 된다.


let threeDoubleQuotationMarks = """
Escaping the first quotation mark \"""
Escaping all three quotation marks \"\"\"
"""

Extended String Delimiters

#안에 문자열을 넣어주면 위 처럼 \를 사용하지 않고 특수문자를 사용할 수 있다.


let text = #"Line 1 \nLine 2"# // Line1 \nLine2 출력
let text = #"Line 1 \#nLine 2"# // Line1 개행 Line2 출력
let text = ###"Line 1 \###nLine 2"### // Line1 개행 Line2 출력

여러 줄의 문자열에도 동일


let threeMoreDoubleQuotationMarks = #""" 
Here are three more double quotes: """ 
"""#

Initializing an Empty String

빈 문자열 선언


var emptyString = "" // empty string literal var anotherEmptyString = String() // initializer syntax // these two strings are both empty, and are equivalent to each other

String Mutablilty

String을 var로 선언 시 수정 가능, let으로 선언 시 수정 불가.


var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"

let constantString = "Highlander"
constantString += " and another Highlander"
// this reports a compile-time error - a constant string cannot be modified

Working with Characters

for-in loop 으로 String을 Character로 표현 가능.


for character in "Dog!🐶" { 
    print(character) 
} 
// D 
// o 
// g 
// ! 
// 🐶

선언 시 Character을 선언하여 하나의 문자 사용 가능하고 Character 배열로 String값을 생성 가능.


//하나의 문자
let exclamationMark: Character = "!"

//Character 배열로 String 생성.
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"] 
let catString = String(catCharacters) 
print(catString) 
// Prints "Cat!🐱"

Concatenating Strings and Characters

String은 +연산자나 +=, append()메소드를 사용하여 추가할 수 있다.


let string1 = "hello" 
let string2 = " there" 
var welcome = string1 + string2 // welcome now equals "hello there"

var instruction = "look over" 
instruction += string2 // instruction now equals "look over there"

let exclamationMark: Character = "!" 
welcome.append(exclamationMark) // welcome now equals "hello there!"

String Interpolation

String에 상수,변수,리텉럴,연산 등의 값을 넣는 것. ()으로 넣으면 된다

let multiplier = 3 
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" 
// message is "3 times 2.5 is 7.5

만약 #이 문자열 앞뒤에 붙어있다면 보간법이 사용 불가능.

Accessing and Modifying a String

String Indices

String은 Index타입이다. String내의 각 Character를 접근할 때 Int형이 아닌 String.index형태로 접근.
각각의 문자가 다른 메모리 양을 가지고 있어서 Swift 문자열은 정수 값으로 인덱스를 생성할수 없다.

startIndex : String의 첫 Character에 접근하는 위치.
endIndex : String의 마지막 Character에 접근하는 위치
String이 비었다면 startIndex == endIndex이다.

String의 index(before:)이나 index(after:)메소드로도 인덱스에 접근 가능.
index(_:offsetBy) 메소드를 통해 여러 문자를 한번에 뛰어 넘을 수 있다.


let greeting = "Guten Tag!" 
greeting[greeting.startIndex] // G 
greeting[greeting.index(before: greeting.endIndex)] // ! 
greeting[greeting.index(after: greeting.startIndex)] // u 
let index = greeting.index(greeting.startIndex, offsetBy: 7) 
greeting[index] // a

String의 범위가 벗어난 index에 접근하면 에러 발생

greeting[greeting.endIndex] // Error greeting.index(after: greeting.endIndex) // Error

String의 indices 프로퍼티를 이용해 문자열의 모든 인덱스에 접근 가능.

for index in greeting.indices {
	print("\(greeting[index])", terminaor: "")
}
//prints "G u t e n T a g!"

Collection 프로토콜로 만들어진 타입(String,Array,Dictionary,Set) 또한 startIndex,endIndex,index(before:),index(after:),index(_:offsetBy:) 사용 가능.

Insert and Removing

String의 특정 index에 Character을 삽입하기 위해서 insert(_:at:)메소드를 사용,
특정 String을 삽입하려고 한다면 insert(contentsOf:at:) 메소드 사용


var welcome = "hello"
welcome.insert("!",at:welcome.endIndex) // "hello!"

welcome.insert(contentsOf:"there", at:welcome.index(before:welcome.endIndex)) // "hello there!"

특정 index의 Character을 제거하기 위해선 remove(at:) 메소드 사용,
특정 범위의 substring을 제거하기 위해선 removeSubrange(_:) 메소드 사용

welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"

let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
//endIndex의 글자를 포함한 6개
welcome.removeSubrange(range)
// welcome now equals "hello"

언급한 insert,remove method들 또한 String,Array,Dictionary,Set에서 사용 가능

Substring

String에서 substring을 얻을 때 prefix같은 메소드를 사용하면 substring 인스턴스가 된다.
substring은 매우 짧은 시간동안만 사용해서 오랜 시간동안 사용하고 싶다면 substring을 string으로 만들어줘야 한다.


let greeting = "Hello, world!" 
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex 
let beginning = greeting[..<index] // beginning is "Hello" 

// Convert the result to a String for long-term storage. 
let newString = String(beginning)

Comparing Strings

Prefix and Suffix Equality

접두사나 접미사 확인하려면 hasPrefix(:),hasSuffix(:)를 사용.


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 romeoAndJuliet { 
	if scene.hasPrefix("Act 1 ") { 
    act1SceneCount += 1 
    } 
} 
print("There are \(act1SceneCount) scenes in Act 1") 
// Prints "There are 5 scenes in Act 1"

hasPrefix(_:)를 통해 접두사 존재하는 String 확인.


var mansionCount = 0 
var cellCount = 0 
for scene in romeoAndJuliet { 
	if scene.hasSuffix("Capulet's mansion") { 
    	mansionCount += 1 
    } else if scene.hasSuffix("Friar Lawrence's cell") { 
    	cellCount += 1 
    } 
} 
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes") 
// Prints "6 mansion scenes; 2 cell scenes"

hasSuffix(_:) 똑같이 사용하면 된다.

0개의 댓글