개발 일기

Strings and Characters 본문

컴퓨터 언어/swift

Strings and Characters

이건욱

Swift에서 String은 다음과 같이 초기화 할수 있습니다.

var emptyString = ""               // empty string literal
var anotherEmptyString = String()  // initializer syntax

 

여러줄을 사용하고 싶은 경우에는 다음과 같이 할수 있습니다.

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

문자열안에 변수를 넣고 싶으면 다음과 같이 할수 있습니다.

let softWrappedQuotation = "\(temp)"

문자열안에서 \n (다음줄) \\(백슬래시) 등등 다음과 같이 표시가 가능합니다.

let temp = "hello \n world"

문자열에 \n ... 이런 효과를 나타나지 않고 포함하고 싶은 경우에는 다음과 같이 할수가 있습니다.

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

 

문자열이 비어있는지 확인 하고 싶은 경우에는 다음과 같이 할수가 있습니다.

if emptyString.isEmpty {
    print("Nothing to see here")
}

상수 및 변수 표시 방법

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

문자열 반복은 다음과 같이 진행이 가능합니다.

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

그리고 String값에 다음과 같은 배열을 넣을수도 있습니다.

let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!🐱"

 

 

문자열 변경

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

var instruction = "look over"
instruction += string2

let exclamationMark: Character = "!"
welcome.append(exclamationMark)

et badStart = """
one
two
"""
let end = """
three
"""
print(badStart + end)
// Prints two lines:
// one
// twothree

let goodStart = """
one
two

"""
print(goodStart + end)
// Prints three lines:
// one
// two
// three

문자열 길이 확인은 다음과 같이 가능합니다.

let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
print("unusualMenagerie has \(unusualMenagerie.count) characters")

 

문자열을 특정 위치를 다음과 같이 얻어올수 있습니다.

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

문자열 삭제 및 추가는 다음과 같이 진행이 가능합니다.

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

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

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

let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"

문자열 자르기는 다음과 같이 진행이 가능합니다.

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)

 

문자열 비교

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    print("These two strings are considered equal")
}
// Prints "These two strings are considered equal"

 

접두사 확인

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"

접미사 확인

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"

 

'컴퓨터 언어 > swift' 카테고리의 다른 글

Closures ?  (0) 2020.05.17
Function ?  (0) 2020.05.16
Control Flow ?  (0) 2020.05.10
Collection Type ?  (0) 2020.05.03
기본적입 타입 소개 ?  (0) 2020.04.25
Comments