Swift专栏---字符串.无论OC还是Swift,甚至其他语言,字符串是运用最多的数据类型,今天我们就来看看Swift中的字符串:String!!!喜欢的小伙伴,可以关注我.
//1:字符串的定义
var str = "Hello, playground"
//在实际开发过程中经常用可选项配合
var string1 :String?
string1 = "Cooci"
//2:判断两个字符串比较
// == 完美抛弃烦人的 isEqualTo
if string1 == str{
print("相同的字符串")
}
字符串比较
使用的是字典序的方式比较。字典序靠后的较大
//3:字符串前缀,后缀
let arrayTest = ["cooci","cc","james","123","gavin","adoft","vergil","dfsg"]
var count:Int = 0
for s in arrayTest{
if s.hasPrefix("c"){
print(s)
}
if s.hasSuffix("s") {
print(s)
}
}
//4、连接字符串和字符
let string3 = "hello"
let string4 = " word"
var welcome = string3 + string4
//append也可以
welcome.append("Cooci")
这种直接字符串拼接大大简化操作: "+"
//5:访问和修改字符串
var string5 = "Swifthelloword"
print(string5[string5.startIndex])
//5.1删除字符串中特定的字符
//拿到开始索引
let index = string5.index(string5.startIndex, offsetBy: 3)
string5.remove(at: index)
print(string5[index])
//结束索引
let index2 = string5.index(string5.startIndex, offsetBy: 5)
//这个方法是传String.index的类型
//其中特别说明一下 index...index2 代表区间 这个经常用在for-in循环
string5.removeSubrange(index...index2)
//5.2字符串替换
string5.replaceSubrange(index...index2, with: "Cooic")
let index3 = string5.index(string5.startIndex, offsetBy: 6)
//5.3字符串插入
string5.insert(contentsOf: "Nice", at: index3)
//6.大写和小写字符串
let string6 = "cooci,hello"
//全部大写
string6.uppercased()
//首字母大写,其他都小写(根据标点来)
string6.capitalized
//全部小写
string6.lowercased()
//7:字符转字符串
var characters : [Character] = ["C","o","o","c","i","🐱","C","o","o","c","i","🐱","C","o","o","c","i"]
let string7 = String(characters)
//上面组合,下面按照🐱分开
string7.split(separator: "🐱")
Swift-day1---HelloWord
Swift-day2---基本数据类型
持续更新!!!如有什么不足,还请不吝指出!谢谢!
网友评论