关于Swift字符串
比较字符串
if( text1 == text2)
String字符串查找
var test="11111111111test"
if (string.rangeOfString("test") != nil) //注意!=左右的空格
{
println("find")
}
如果想获得位置,就:
var t=string.rangeOfString("test")
开始位置
t?.startIndex
结束位置
t?.endIndex
另,再补充个方法,google的
let string = "hello Swift";
let subString = (string as NSString).containsString("Swift")
if(subString){println("Exist")}
String与NSString区别
String 扩展
// 字符串类扩展
extension String {
/// 获取字符串绘制的高度
///
/// - parameter font : 要绘制的字体,将会影响行高等
/// - parameter width : 绘制的宽度
/// - returns : 字符串绘制的最大高度
func getMaxHeight(font:UIFont, width:CGFloat) -> CGFloat {
// 获取最大的
let s = CGSize(width: width, height: CGFloat(MAXFLOAT))
return getMaxHeight(font: font, rangeRect: s)
}
/// 获取字符串绘制的高度
///
/// - parameter font : 要绘制的字体,将会影响行高等
/// - parameter rangeRect : 绘制的最大范围,类似于最大的画布
/// - returns : 字符串绘制的最大高度
func getMaxHeight(font:UIFont, rangeRect rect:CGSize) -> CGFloat {
// draw option
let opt:NSStringDrawingOptions = [NSStringDrawingOptions.truncatesLastVisibleLine, NSStringDrawingOptions.usesFontLeading, NSStringDrawingOptions.usesLineFragmentOrigin]
// str
let str = NSString(string: self)
// max size
let maxSize = rect
// font
let attr:[String:Any] = [NSFontAttributeName:font]
// 计算出来的范围
let resultRect = str.boundingRect(with: maxSize, options: opt, attributes: attr, context: nil)
// 返回高度
return CGFloat(ceil(Double(resultRect.height)))
}
/**
获取字符串的单行宽度,
有可能会超过屏幕限制
- parameter font : 要绘制的字体
*/
func getMaxWidth(font:UIFont) -> CGFloat {
let opt:NSStringDrawingOptions = [NSStringDrawingOptions.truncatesLastVisibleLine, NSStringDrawingOptions.usesFontLeading, NSStringDrawingOptions.usesLineFragmentOrigin]
// str
let str = NSString(string: self)
// max size
let maxSize = CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT))
// font
let attr:[String:Any] = [NSFontAttributeName:font]
// 计算出来的范围
let resultRect = str.boundingRect(with: maxSize, options: opt, attributes: attr, context: nil)
// 返回高度
return CGFloat(ceil(Double(resultRect.width)))
}
/**
去除左右的空格和换行符
*/
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/**
将字符串通过特定的字符串拆分为字符串数组
- parameter str : 拆分数组使用的字符串
- returns : 字符串数组
*/
func split(string:String) -> [String] {
return NSString(string: self).components(separatedBy: string)
}
/**
拆分字符串,并获取指定索引的字符串
- parameter splitStr : 拆分数组使用的字符串
- parameter index : 索引位置
- parameter defaultStr : 默认字符串
- returns : 拆分所得字符串
*/
func strSplitByIndex(splitStr str:String, index:Int, defaultStr:String = "") -> String {
let a = self.split(string:str)
if index > a.count - 1 {
return defaultStr
}
return a[index]
}
/**
字符串替换
- parameter of : 被替换的字符串
- parameter with : 替换使用的字符串
- returns : 替换后的字符串
*/
func replace(of: String, with: String) -> String {
return self.replacingOccurrences(of: of, with: with)
}
/**
判断是否包含,虽然系统提供了方法,这里也只是简单的封装。如果swift再次升级的话,就知道现在做的好处了
- parameter string : 是否包含的字符串
- returns : 是否包含
*/
func has(string:String) -> Bool {
return self.contains(string)
}
/**
字符出现的位置
- parameter string : 字符串
- returns : 字符串出现的位置
*/
func indexOf(string str:String) -> Int {
var i = -1
if let r = range(of: str) {
if !r.isEmpty {
i = characters.distance(from: self.startIndex, to: r.lowerBound)
}
}
return i
}
/**
这个太经典了,获取指定位置和大小的字符串
- parameter start : 起始位置
- parameter length : 长度
- returns : 字符串
*/
func subString(start:Int, length:Int = -1) -> String {
var len = length
if len == -1 {
len = characters.count - start
}
let st = characters.index(self.startIndex, offsetBy:start)
let en = characters.index(st, offsetBy:len)
let range = st ..< en
return self.substring(with:range)
}
/// 字符串的长度
var length:Int {
get {
return self.characters.count
}
}
/// 将16进制字符串转为Int
var hexInt:Int {
get {
return Int(self, radix: 16) ?? 0
}
}
}
1、 字符串长度: 3种方法。
let str = "12345678"
let len1 = strlen(str) //8
let len2 = str.count //8
let len3 = (str as NSString).length //8
2、字符串拼接: 使用加好或者append函数。
let str1 = "abc" + "cde"
var str = "abc"
str.append("cde")
3、字符串遍历:
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)")
}
4、字符串全部大写或小写:
let str = "abcdefg"
print(str.lowercased()) //全部小写
print(str.uppercased()) //全部大写
5、多行字符串使用3个双引号。
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!..<str.endIndex] //defg 注意避免下标越界
let sub2 = str[str.startIndex...indexD!] //abcd
或
let sub3 = (str as NSString).substring(to: 3) //abc
let sub4 = (str as NSString).substring(with: NSMakeRange(2, 3)) //cde
8、判断是否含有字符(串)
let str = "abcdefg"
print(str.contains("cd")) //true
print(str.contains("c")) //true
print(str.contains("o")) //false
9、字符串分割
//字符串拆分(以单个或多个字符为分隔符)
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)
进阶篇:
1、获取下标字符:
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
2、找出字符串中最长的子串, 字符串中包含中文、特殊字符、字母、数字等等。 思路: 使用正则找出所有字符串, 然后按长度排序找到最长的。
//找出字符串中英文字母最长的一个
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
3、字符串首字母变成大写(考虑字符串中有标点符号):
//首字母大写, 要求支持标点
func LetterCapitalize(_ str: String) -> String {
var result = ""
for i in 0..<str.count{
let cur = str.charAt(pos: i)
if i == 0 {
let tmp = String(cur!).uppercased() //变成大写
result.append(tmp)
} else {
let pre = str.charAt(pos: i-1)
//if pre is not character
if (UnicodeScalar(String(pre!))!.value >= 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
}
}
相关资料:
Swift String常用方法:
https://blog.csdn.net/brycegao321/article/details/78722368