그래오늘은이거야

Swift 문자열 다루기 (비교/찾기 등등) 본문

세상 개발/IOS(Swift)

Swift 문자열 다루기 (비교/찾기 등등)

jinhongstar 2020. 6. 10. 10:34
728x90
반응형

자주 사용 하는 Swift 문법 정리

문자열 표현

let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]

let catString = String(catCharacters)

print(catString)

// Prints "Cat!🐱"

 

문자열 삽입

let mutiplier = 3

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

// message : "3 times 2.5 is 7.5"

 

문자열 찾기

 

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

 

greeting[greeting.endIndex] // 에러!

greeting.index(after: greeting.endIndex) // 에러!

 

for index in greeting.indices {

print("\(greeting[index]) ", terminator: "")

// G u t e n T a g !

 

문자 삽입 삭제

var welcome = "hello"

welcome.insert("!", at: welcome.endIndex)

// welcome : hello!

 

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

// welcome : hello there!

 

welcome.remove(at: welcome.index(before: welcome.endIndex))

// welcome : hello there

 

let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex

welcome.removeSubrange(range)

// welcome : hello

 

부분 문자열

let greeting = "Hello, World!"

let index = greeting.index(of: ",") ?? greeting.endIndex

let beginning = greeting[..<index]

// beginning : Hello

 

// SubString인 beginning을 String으로 변환

let newString = String(beginning)

 

문자열 비교

let quotation = "We're a lot alike, you and I."

let sameQuotation = "We're a lost alike, you and I."

if quotation == sameQuotation {

print("These two strings are considered equal")

}

 

문자열 접두사 접미사

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"

]

 

몇개 있는지 찾는다 Act 1

var act1SceneCount = 0

for scene in remeoAndJuliet {

if scene.hasPrefix("Act 1 ") {

act1SceneCount += 1

}

}

print("There are \(act1SceneCount) scenes in Act 1")

// There are 5 scenes in Act 1

 

참고 사이트 

https://jusung.gitbook.io/the-swift-language-guide/language-guide

반응형
Comments