Swift-字符串:String 的操作
发布时间:2020-12-14 07:10:28 所属栏目:百科 来源:网络整理
导读:1.判断是否是空值 //判断是否是空值 let str :String = "" if str .isEmpty{ print( "str is nil" ) }打印结果: str is nil let str1:String = "hahahaha" if str1.isEmpty{ print( "str is nil" ) } else { print( "str is ( str1)" ) } 打印结果: str i
1.判断是否是空值 //判断是否是空值
let str:String = ""
if str.isEmpty{
print("str is nil")
}
打印结果:str is nil
let str1:String = "hahahaha"
if str1.isEmpty{
print("str is nil")
}else{
print("str is ( str1)")
}
打印结果:str is hahahaha
2.获取字符数量 //获取字符数量
let str:String = "http://www.baidu.com"
print("the num is ( str.characters.count)")
打印结果:the num is 20
3.遍历字符 //遍历字符
let str:String = "http://www.baidu.com"
for charvalue in str.characters{
print("--->(charvalue)")
}
打印结果:
--->h --->t --->t --->p --->: --->/ --->/ --->w --->w --->w --->. --->b --->a --->i --->d --->u --->. --->c --->o --->m
4.字符串是否有特定前缀/后缀 //字符串是否有前后
let str:String = "http://www.baidu.com"
if str .hasPrefix("http://"){
print("hasPrefix--->http://")
}
if str .hasSuffix(".com"){
print("hasSuffix--->.com")
}
打印结果:
hasPrefix--->http://
hasSuffix--->.com
5.大小写转换 //大小写转换
let str = "Hello World!"
//大写
let uppercase = str.uppercaseString
//小写
let lowercase = str.lowercaseString
//首字母大写
let capitalized = str.capitalizedString
print("uppercase--->(uppercase)")
print("lowercase--->(lowercase)")
print("capitalized--->(capitalized)")
打印结果:
uppercase--->HELLO WORLD!
lowercase--->hello world!
capitalized--->Hello World!
6.字符串数组 // 字符串数组
var strArray = [String]()
strArray.append("hello")
strArray.append(" ")
strArray.append("world!")
print("strArray--->(strArray)")
//拼接字符串
print("strArray--->(strArray.joinWithSeparator(""))")
//拆分字符串
let newArray = strArray.split("")
print("strArray--->(newArray)")
打印结果:
strArray--->["hello"," ","world!"]
strArray--->hello world!
strArray--->[[ArraySlice(["hello","world!"])]]
7.字符数组删除 //字符数组删除
var strArray = ["hello","world","!"]
print("strArray--->(strArray)")
//删除第一个
strArray.removeFirst()
print("strArray--->(strArray)")
//删除最后一个
strArray.removeLast()
print("strArray--->(strArray)")
//删除指定下标的元素
strArray .removeAtIndex(0)
print("strArray--->(strArray)")
//删除所有元素
strArray .removeAll()
print("strArray--->(strArray)")
打印结果:
strArray--->["hello","!"]
strArray--->[" ","world"]
strArray--->["world"]
strArray--->[]
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |