1. 创建字符串:
var str = "Hello, Swift!"
2. 连接字符串:
var firstName = "John"
var lastName = "Doe"
var fullName = firstName + " " + lastName
也可以使用字符串插值:
var age = 25
var message = "My name is \(fullName) and I am \(age) years old."
3. 字符串长度:
let length = fullName.count
4. 字符串比较:
var str1 = "abc"
var str2 = "def"
if str1 == str2 {
print("相等")
} else {
print("不相等")
}
5. 字符串截取和子串:
let greeting = "Hello, World!"
let startIndex = greeting.startIndex
let endIndex = greeting.index(startIndex, offsetBy: 5)
let substring = greeting[startIndex..<endIndex]
print(substring) // 输出 "Hello"
6. 字符串转换为数组:
let word = "Swift"
let characters = Array(word)
print(characters) // 输出 ["S", "w", "i", "f", "t"]
7. 字符串的常见方法:
var sentence = "This is a sample sentence."
// 判断前缀和后缀
if sentence.hasPrefix("This") {
print("以'This'开头")
}
if sentence.hasSuffix("sentence.") {
print("以'sentence.'结尾")
}
// 查找子字符串
if let range = sentence.range(of: "sample") {
print("找到了,位置在 \(range.lowerBound) 到 \(range.upperBound) 之间")
}
这些是一些基本的字符串操作。Swift还提供了丰富的字符串处理功能,可以满足更复杂的需求。
转载请注明出处:http://www.zyzy.cn/article/detail/6842/Swift