Deep_Dev
article thumbnail

๐Ÿ“š String 

๊ตฌ์กฐ์ฒด์ด๊ณ  ๋‹ค๋ฅธ ์–ธ์–ด์™€ ๊ฐ™์ด character๊ฐ€ ๋ชจ์ธ ์ง‘ํ•ฉ

 

 

Array() : ๋ฌธ์ž์—ด -> ๋ฐฐ์—ด

๋ฌธ์ž์—ด์˜ ์š”์†Œ ํ•˜๋‚˜ํ•˜๋‚˜๋ฅผ ๋ฐฐ์—ด๋กœ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•.

let name: String = "SWIFT"
let arrName = Array(name)
print(arrName) // ["S","W","I","F","T"]

 

 

 

count() , empty() : ๋ฌธ์ž์—ด์˜ ๊ธธ์ด ๊ตฌํ•˜๊ธฐ

let string: "A Unicode string value that is a collection of characters."
print(string.count) // 58

let empty = ""
print(empty.isEmpty) // true
print(string.isEmpty) // false

 

 

append() : ๋ฌธ์ž์—ด ํ•ฉ์น˜๊ธฐ

๋ฌธ์ž์—ด์„ ํ•ฉ์น˜๋Š” ๋ฐฉ๋ฒ•์€ ๊ฐ„๋‹จํ•˜๊ฒŒ 2๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค.

var str = "Swift"
str.append(" is Hard.")
print(str) // "Swift is Hard.

var str1 = "ABC"
var str2 = "DEFG"
print(str1 + str2) // "ABCDEFG"

 

 

๋ฌธ์ž์—ด ๋‹ค๋ฃจ๊ธฐ ( ๋Œ€๋ฌธ์ž, ์†Œ๋ฌธ์ž, ์ˆซ์ž์ธ์ง€, ๋ฌธ์ž์ธ์ง€ ํŒŒ์•… )

let str = "lower"
print(str.uppercased()) // "LOWER"

let str = "UPPER"
print(str.lowercased()) // "upper"

let char = "a" as Character
print(char.isNumber) // false
print(char.isLetter) // true
print(char.isUppercase) // false
print(char.isLowercase) // true
print(char.isASCII) // true
print(char.asciiValue) // Optional(97) -> ์–ธ๋ž˜ํ•‘ ํ•ด์ค˜์•ผํ•œ๋‹ค.

let num = "1"
print(num.isNumber) // true

 

 

๋ฌธ์ž์—ด์˜ ์‹œ์ž‘๊ณผ ๋

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๋ณด๋ฉด ์ข…์ข… ๋ฌธ์ž์—ด์˜ ๋งจ ์ฒ˜์Œ๊ณผ ๋์„ ๋‹ค๋ฃจ๊ฒŒ ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์ข…์ข… ์žˆ๋‹ค. ๋˜ ๊ทธ ๋ฌธ์ž๊ฐ€ ๋ฌธ์ž์—ด์— ์กด์žฌํ•˜๋Š”์ง€ ์—ฌ๋ถ€๋„ ์•Œ ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜๊ฐ€ ์žˆ๋‹ค.

var str = "ABCDE"
print(str.hasPrefix("A")) // true -> ์ ‘๋‘์–ด ํŒ๋‹จ
print(str.hasSuffix("E")) // true -> ์ ‘๋ฏธ์–ด ํŒ๋‹จ
print(str.contains("A")) // true -> ์กด์žฌ ํŒ๋‹จ
print(str.first) // Optional("A")
print(str.last) // Optional("E")

.first , last ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๋–„์—๋Š” ์˜ต์…”๋„ ๊ฐ’์ด ์ถœ๋ ฅ๋œ๋‹ค. ๋”ฐ๋ผ์„œ ์–ธ๋ž˜ํ•‘์„ ํ•ด์ค˜์•ผํ•œ๋‹ค. 

 

 

 

init(repeating:count:) : ๋ฌธ์ž ๋ฐ˜๋ณต

String๊ณผ Array์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ฐฐ์—ดํฌ๊ธฐ์™€ ์ดˆ๊ธฐ๊ฐ’์„ ๋„ฃ์–ด์ค„ ์ˆ˜ ์žˆ์œผ๋ฉฐ, ํŠน์ • ๊ฐ’์„ ๋ฐ˜๋ณตํ•˜์—ฌ ๊ฐ’์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

repeating์— ๋ฐ˜๋ณตํ•  ๋ฌธ์ž, ๋ฌธ์ž์—ด, ์ˆซ์ž, ๋ถ€์šธ ๋“ฑ์„ ๋„ฃ์–ด์ฃผ๋ฉด ๋˜๊ณ , count์—๋Š” ๋ฐ˜๋ณต ํšŸ์ˆ˜๋ฅผ ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

 

String

let str = String(repeating:"str", count:3)
print(str) // strstrstr

let ch = Character(readLine()!) // G
print(String(repeating: ch, count:4) / GGGG

Array

// [Int](repeating: 0, count:5)์™€ ๊ฐ™์Œ 
let in = Array(repeating:0, count:5)
print(in) // [0,0,0,0,0]

let in = [String](repeating:"c", count:5)
print(in) //["c","c","c","c","c"]