Chuỗi ký tự (String) trong Swift
1. String Basics
let name = "Swift"
let greeting: String = "Hello"
// Multi-line
let multiLine = """
Line 1
Line 2
"""
// Empty string
let empty = ""
let isEmpty = empty.isEmpty // true2. String Operations
let str = " Swift Programming "
// Case
print(str.uppercased()) // " SWIFT PROGRAMMING "
print(str.lowercased()) // " swift programming "
// Trim
let trimmed = str.trimmingCharacters(in: .whitespaces)
// Contains
print(str.contains("Swift")) // true
// Replace
let replaced = str.replacingOccurrences(of: "Swift", with: "iOS")3. String Indexing
let str = "Swift"
print(str.first) // Optional("S")
print(str.last) // Optional("t")
print(str.count) // 5
// Substring
let index = str.index(str.startIndex, offsetBy: 2)
let sub = str[index...] // "ift"4. Split
let csv = "a,b,c"
let parts = csv.split(separator: ",") // ["a", "b", "c"]📝 Tóm tắt
"""..."""- Multi-line stringsuppercased(),lowercased()- Case conversioncontains(),replacingOccurrences()split(separator:)- Tách chuỗi- String indexing phức tạp hơn các ngôn ngữ khác
Last updated on
Swift