参考Java String类, 对Swift String用法做个总结。
基础篇:
1、 字符串长度: 3种方法。
let str = "12345678"
let len1 = strlen(str) //8
let len2 = str.count //8
let len3 = (str as NSString).length //8
let str1 = "abc" + "cde"
var str = "abc"
str.append("cde")
let str = "abcdefg"
for char in str {
print(char)
}
let str = "abcdefg"
for index in str.indices.indices {
print(str[index]) //通过下标访问
}
或带下标
let str = "abcdefg"
for (index, value) in str.enumerated() {
print("\(index) --- \(value)")
}
let str = "abcdefg"
print(str.lowercased()) //全部小写
print(str.uppercased()) //全部大写
let verse = """
To be, or not to be - that is the question;
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
"""
6、ascii码
let ascii = UnicodeScalar("a")?.value //a的ascii码
print(ascii ?? "") //97
7、截取子字符串
let str = "abcdefg"
let indexD = str.index(of: "d")
let sub = str[indexD!...] //defg
let sub1 = str[indexD!..
或
let sub3 = (str as NSString).substring(to: 3) //abc
let sub4 = (str as NSString).substring(with: NSMakeRange(2, 3)) //cde
let str = "abcdefg"
print(str.contains("cd")) //true
print(str.contains("c")) //true
print(str.contains("o")) //false
//字符串拆分(以单个或多个字符为分隔符)
let str = "abcdefg$$aaaa$$bbbb$$ccc"
let des1 = (str as NSString).components(separatedBy: "$$")
let des2 = str.components(separatedBy: "$$")
print(des1) //["abcdefg", "aaaa", "bbbb", "ccc"]
print(des2) //["abcdefg", "aaaa", "bbbb", "ccc"]
10、字符串替换:
let str = "abcdefg$$aaaa$$bbbb$$ccc"
let dest11 = str.replacingOccurrences(of: "$$", with: "**")
print(dest11)
extension String {
//获取下标对应的字符
func charAt(pos: Int) -> Character? {
if pos < 0 || pos >= count {
return nil //判断边界条件
}
let index = self.index(self.startIndex, offsetBy: pos)
let str = self[index]
return Character(String(str))
}
}
let str = "abcdef"
print(str.charAt(pos: 1)!) //b
//找出字符串中英文字母最长的一个
func LongestWord(_ sen: String) -> String {
let regx = try? NSRegularExpression(pattern: "[a-zA-Z]+", options: .caseInsensitive)
if let results = regx?.matches(in: sen, options: [], range: NSMakeRange(0, sen.count)) {
var array: [String] = []
for item in results {
let cur = (sen as NSString).substring(with: item.range)
array.append(cur) //找出所有符合要求的字符串
}
array.sort(by: { a,b in
if a.count > b.count { //降序排列
return true
} else {
return false
}
})
return array[0] //最长的字符串
}
return sen
}
let ret = LongestWord("this is a test demo.1234324234穿插着中文和特殊字母@#@#adfsdfsdf!@#@$adfsdf")
print(ret) //adfsdfsdf
//首字母大写, 要求支持标点
func LetterCapitalize(_ str: String) -> String {
var result = ""
for i in 0..= UnicodeScalar("a")!.value && UnicodeScalar(String(pre!))!.value <= UnicodeScalar("z")!.value)
|| (UnicodeScalar(String(pre!))!.value >= UnicodeScalar("A")!.value && UnicodeScalar(String(pre!))!.value <= UnicodeScalar("Z")!.value){
result.append(String(cur!))
} else {
result.append(String(cur!).uppercased())
}
}
}
return result
}
let ret = LetterCapitalize("this a test message")
print(ret)
4、获取UILable控件显示String需要的高度
extension String {
/**
* 查询lable高度
* @param fontSize, 字体大小
* @param width, lable宽度
*/
func getLableHeightByWidth(_ fontSize: CGFloat,
width: CGFloat,
font: UIFont) -> CGFloat {
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
let attributes = [NSFontAttributeName:font,
NSParagraphStyleAttributeName:paragraphStyle.copy()]
let text = self as NSString
let rect = text.boundingRect(with: size, options:.usesLineFragmentOrigin, attributes: attributes, context:nil)
return rect.size.height
}
}