으니의 개발로그

[Swift] String 타입의 다양한 기능 본문

Swift/책 정리

[Swift] String 타입의 다양한 기능

아잉으니야 2021. 1. 6. 21:00

[Swift] String 타입의 다양한 기능

이 글은 Swift 프로그래밍 책을 읽고 요약한 내용입니다.

 

연산자를 통한 문자열 결합

let hello: String = "Hello"
let seonho: String = "seonho"
var greeting: String = hello + " " + seonho + "!"
print(greeting)
/* Hello seonho! */

greeting = hello
greeting += " "
greeting += seonho
greeting += "!"
print(greeting)
/* Hello seonho! */

 

연산자를 통한 문자열 비교

var isSameString: Bool = false

isSameString = hello == "Hello"
print(isSameString)
/* true */

isSameString = hello == "hello"
print(isSameString)
/* false */

isSameString = seonho == "seonho"
print(isSameString)
/* true */

isSameString = seonho == hello
print(isSameString)
/* false */

 

메서드를 통한 접두어, 접미어 확인

var hasPrefix: Bool = false
hasPrefix = hello.hasPrefix("He")
print(hasPrefix)
/* true */

hasPrefix = hello.hasPrefix("HE")
print(hasPrefix)
/* false */

hasPrefix = greeting.hasPrefix("Hello ")
print(hasPrefix)
/* true */

hasPrefix = seonho.hasPrefix("ho")
print(hasPrefix)
/* false */

hasPrefix = hello.hasPrefix("Hello")
print(hasPrefix)
/* true */

var hasSuffix: Bool = false
hasSuffix = hello.hasSuffix("He")
print(hasSuffix)
/* false */

hasSuffix = hello.hasSuffix("llo")
print(hasSuffix)
/* true */

hasSuffix = greeting.hasSuffix("seonho")
print(hasSuffix)
/* false */

hasSuffix = greeting.hasSuffix("seonho!")
print(hasSuffix)
/* true */

hasSuffix = seonho.hasSuffix("ho")
print(hasSuffix)
/* true */

 

메서드를 통한 대소문자 변환

var convertedString: String = ""
convertedString = hello.uppercased()
print(convertedString)
/* HELLO */

convertedString = hello.lowercased()
print(convertedString)
/* hello */

convertedString = seonho.uppercased()
print(convertedString)
/* SEONHO */

convertedString = greeting.uppercased()
print(convertedString)
/* HELLO SEONHO! */

convertedString = greeting.lowercased()
print(convertedString)
/* hello seonho! */

 

프로퍼티를 통한 빈 문자열 확인

var isEmptyString: Bool = false
isEmptyString = greeting.isEmpty
print(isEmptyString)
/* false */

greeting = "안녕"
isEmptyString = greeting.isEmpty
print(isEmptyString)
/* false */

greeting = ""
isEmptyString = greeting.isEmpty
print(isEmptyString)
/* true */

 

프로퍼티를 이용해 문자열 길이 확인

print(greeting.count)
/* 0 */

greeting = "안녕하세요"
print(greeting.count)
/* 5 */

greeting = "안녕!"
print(greeting.count)
/* 3 */

 

여러 줄의 문자

// 코드상에서 여러 줄의 문자를 직접 쓰고 싶다면 큰따옴표 세 개를 사용하면 됨
// 큰따옴표 세 개를 써주고 한 줄을 내려써야 함
// 마지막 줄도 큰따옴표 세 개는 한 줄 내려써야 함
greeting = """
    안녕하세요 저는 선호입니다.
    스위프트를 잘하고 싶어요!
    잘 부탁합니다!
    """