Swift 中的字符串处理有哪些常用方法?如何进行字符串的拼接、截取、替换和查找?
Swift 提供了丰富的字符串处理方法,包括拼接、截取、替换、查找等操作。Swift 的字符串类型是值类型,支持 Unicode 字符。
字符串拼接:
swift// 使用 + 运算符 let str1 = "Hello" let str2 = "World" let combined = str1 + ", " + str2 // "Hello, World" // 使用 += 运算符 var greeting = "Hello" greeting += ", World" // "Hello, World" // 使用字符串插值 let name = "John" let age = 30 let message = "My name is \(name) and I'm \(age) years old" // 使用 append 方法 var text = "Hello" text.append(", World") // "Hello, World"
字符串截取:
swiftlet str = "Hello, World" // 使用 prefix 和 suffix let prefix = str.prefix(5) // "Hello" let suffix = str.suffix(6) // "World" // 使用 dropFirst 和 dropLast let withoutFirst = str.dropFirst() // "ello, World" let withoutLast = str.dropLast() // "Hello, Worl" // 使用索引 let startIndex = str.startIndex let endIndex = str.index(str.startIndex, offsetBy: 5) let substring = str[startIndex..<endIndex] // "Hello" // 使用 range let range = str.range(of: "World")! let substring2 = str[range] // "World"
字符串替换:
swiftlet str = "Hello, World" // 替换单个字符 let replaced = str.replacingOccurrences(of: "World", with: "Swift") // "Hello, Swift" // 使用闭包替换 let replaced2 = str.replacingOccurrences(of: "o", with: "O") // "HellO, WOrld" // 使用闭包进行复杂替换 let replaced3 = str.replacingOccurrences(of: "[aeiou]", with: "", options: .regularExpression) // "Hll, Wrld"
字符串查找:
swiftlet str = "Hello, World" // 检查是否包含 let containsHello = str.contains("Hello") // true let containsSwift = str.contains("Swift") // false // 查找子字符串 if let range = str.range(of: "World") { print("Found at range: \(range)") } // 查找前缀和后缀 let hasPrefix = str.hasPrefix("Hello") // true let hasSuffix = str.hasSuffix("World") // true // 查找字符 let firstIndex = str.firstIndex(of: ",") // Optional(String.Index)
字符串分割:
swiftlet str = "apple,banana,orange" // 按字符分割 let components = str.components(separatedBy: ",") // ["apple", "banana", "orange"] // 按字符集分割 let whitespace = "Hello World" let words = whitespace.components(separatedBy: .whitespaces) // ["Hello", "World"]
字符串大小写转换:
swiftlet str = "Hello, World" let uppercased = str.uppercased() // "HELLO, WORLD" let lowercased = str.lowercased() // "hello, world" let capitalized = str.capitalized // "Hello, World"
字符串修剪:
swiftlet str = " Hello, World " let trimmed = str.trimmingCharacters(in: .whitespaces) // "Hello, World" let trimmed2 = str.trimmingCharacters(in: .whitespacesAndNewlines) // "Hello, World"
字符串长度和字符:
swiftlet str = "Hello, World" let count = str.count // 13 let isEmpty = str.isEmpty // false let firstChar = str.first // Optional("H") let lastChar = str.last // Optional("d") let chars = Array(str) // ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d"]
最佳实践:
- 使用字符串插值提高可读性
- 注意字符串索引的使用
- 使用 contains、hasPrefix、hasSuffix 进行快速检查
- 使用 replacingOccurrences 进行字符串替换
- 注意 Unicode 字符的处理