본문 바로가기
Smart Device/Swift

Swift String

by 언덕너머에 2014. 6. 11.

- String  생성하기

* init()

  빈 문자열 초기화

  let emptyString = String()

  위 구문과 아래 구문은 동일하다.

  let equivalentString = ""


- Querying a String

* var isEmpty { get }

  문자열이 비어있는지를 결정하는 Boolean 값

  var isEmpty: Bool { get }


  예)

  var string = "Hello, world!"

  let firstCheck = string.isEmpty

  // firstCheck is false

 

  string = ""

  let secondCheck = string.isEmpty

  // secondCheck is true


* hasPrefix(_ :) -> Bool

  문자열의 처음이 주어진 문자열과 같은지 여부를 Boolean으로 반환

  func hasPrefix(prefix: String) -> Bool


  예)

  let string = "Hello, world"

  let firstCheck = string.hasPrefix("Hello")

  // firstCheck is true

 

  let secondCheck = string.hasPrefix("hello")

  // secondCheck is false


* hasSuffix(_ :) -> Bool

  문자열의 마지막이 주어진 문자열과 같은지 여부를 Boolean으로 반환

  func hasSuffix(prefix: String) -> Bool


  예)

  let string = "Hello, world"

  let firstCheck = string.hasSuffix("world")

  // firstCheck is true

 

  let secondCheck = string.hasSuffix("World")

  // secondCheck is false


- 문자열 변경과 변환

* var uppercaseString { get }

  주어진 모든 문자열을 대문자로 변환합니다.


  예)

  let baseString = "hello world"

  let uppercaseString = baseString.uppercaseString

  // uppercaseString is "HELLO WORLD"


* var lowercaseString { get }

  주어진 모든 문자열을 소문자로 변환합니다.


  예)

  let baseString = "HELLO WORLD"

  let lowercaseString = baseString.lowercaseString

  // lowercaseString is "hello world"


* toInt() -> Int?

  문자열을 정수로 변환하여 반환

  func toInt() -> Int?


  예)

  let string = "42"

  if let number = string.toInt() {

      println("Got the number: \(number)")

  } else {

      println("Couldn't convert to a number")

  }

  // prints "Got the number: 42"  


- Operators

* +


  예)

  let combination = "Hello " + "world"

  // combination is "Hello world"


* +=

 

 예)

  var string = "Hello "

  string += "world!"

  // string is "Hello world!"

  var character: Character = "?"

  string += character

  // string is "Hello world!?"


* ==


  예)

  let string1 = "Hello world!"

  let string2 = "Hello" + " " + "world" + "!"

  let result = string1 == string2

  // result is true


* <


  예)

  let string1 = "Number 3"

  let string2 = "Number 2"

 

  let result1 = string1 < string2

  // result1 is false

 

  let result2 = string2 < string1

  // result2 is true

'Smart Device > Swift' 카테고리의 다른 글

Swift Array #2  (0) 2014.06.11
Swift Array #1  (0) 2014.06.11
Swift Subscript  (0) 2014.06.11
Swift 연산자  (0) 2014.06.10
Swift Objects and Classes #1  (0) 2014.06.09