func someMethodOfRange() {
/**
* 字符串与Range的用法
*/
//1.截取字符串(字符)在整个字符串中所在的位置,返回的类型为 Index
var str = "abcdefghi"
let startIndex = str.rangeOfString("cde")!.startIndex
print(startIndex)//2
let endIndex = str.rangeOfString("cde")!.endIndex
print(endIndex)//5
//2、根据字符串的索引来获取对应的字符
let text = "abcdefghi"
let index2 = text.startIndex.advancedBy(2) //will call succ 2 times
print(index2)//2
let lastChar: Character = text[index2] //now we can index!
print(lastChar)//c
let lastChar2 = text.characters[index2] //will do the same
print(lastChar2)//c
//3.截取字符串(字符)在整个字符串中所在的范围 、返回值类型 Range<Index>
let range: Range<String.Index> = text.rangeOfString("bc")!
print(range)//1..<3
let index3: Int = text.startIndex.distanceTo(range.startIndex)
print(index3)//1
let index4: Int = text.startIndex.distanceTo(range.endIndex)
print(index4)//3
print(text.characters.count)//9
let abc = "@救123"
print(abc.characters.count)//5
//4.0 Index --> Int
let range: Range<String.Index> = self.text!.rangeOfString(text)!
let index3: Int = self.text!.startIndex.distanceTo(range.startIndex)
let index4: Int = self.text!.startIndex.distanceTo(range.endIndex)
//一个字符串。指标值可以通过调用predecessor()方法访问其 先前 指标,其指标successor()下一个指标 调用方法。字符串中的任何指标可从任何其他指数通过把这些方法结合在一起,或通过使用--(_:)方法。试图访问一个字符串的范围以外的索引会引发一个运行时错误
let greeting = "123456789"
greeting[greeting.startIndex]
print(greeting)
print("起使位置\(greeting.startIndex)")//0
print("终点位置\(greeting.endIndex)")//9
print(greeting[greeting.startIndex])//1
greeting[greeting.endIndex.predecessor()]
print(greeting[greeting.endIndex.predecessor()])//9
print(greeting.endIndex.predecessor())//8
print(greeting.startIndex.successor())//1
greeting[greeting.startIndex.successor()]
print(greeting[greeting.startIndex.successor()])//2
let index = greeting.startIndex.advancedBy(7)
greeting[index]
print(greeting[index])//8
//试图在字符串的范围以外的索引处访问一个字符,将引发一个运行时错误。”
//greeting[()]//cuowu
//print(greeting[])//cuowu
//越界
//greeting[]
//()
//““Use the <indices> property of the <characters> property to 创建一个字符串中访问单个字符的所有索引的范围。”
for index in greeting.characters.indices {
print("\(greeting[index])",terminator: "")
// print("**")
}
}
//相关的应用:在UILabel里面,不同文本显示不同字体的大小
extension UILabel {
/*
*设置text的字体大小
*/
func settingLabelTextKitWithText(text:String,font:UIFont) {
if text.isEmpty {//通过检查其 Boolean 类型的 isEmpty 属性来判断该字符串是否为空:
print("什么都没有")
return
}else {
//方法1
let attrstring:NSMutableAttributedString = NSMutableAttributedString(string: self.text!)
let str = NSString(string: self.text!)
let theRange = str.rangeOfString(text)
attrstring.addAttribute(NSFontAttributeName, value: font, range: theRange)
self.attributedText = attrstring
/**
// 方法2
let attrstring:NSMutableAttributedString = NSMutableAttributedString(string: !)
let range: Range<> = !.rangeOfString(text)!
let index3: Int = !.()
let index4: Int = !.()
(NSFontAttributeName, value: font, range: NSMakeRange(index3, index4 - index3))
= attrstring
*/
}
}