原创blog,转载请注明出处
String
在swfit中,String兼容Unicode的方式。使用方法和C语言类似。
注意
在Cocoa和Cocoa touch中,Swift的String,和Foundation中的NSString是兼容的,所有NSString额API都可以调用String类型
字符串常量
1、含转义字符:例如\n,\t等
2、单字节Unicode标量,\xmm
3、双字节Unicode标量,\ummmm
4、四字节Unicode标量,\Ummmmmmmm
这里的m为十六进制数
let myname = "Hwc"//hwc let myname = "\"Hwc\""//"hwc"
var emptyString = "" //空字符串 var sameEmptyString = String()//空字符串 var notEmptyString = "first"
let str = "" if str.isEmpty{ println("This is empty") }
let str = "Hello world" println(str.endIndex)//11
println(countElements(str))
var str = "123" var result = str.toInt() if result != nil{ println("Success") }
4 子字符串
subStringFromIndex(index:String.index) subStringToIndex(index:String.index) subStringWithRange(aRange:Range())这里要使用到一个advance函数: advance(start:T,n:Distance)
var str = "hello world" str.substringFromIndex(advance(str.startIndex,6))//hello str.substringToIndex(advance(str.startIndex,5)) //world str.substringWithRange(Range(start:advance(str.startIndex,2),end:advance(str.startIndex,8)))//llo wo
很简答,用加号+ 或者字符串插值
var str1 = "hello" var str2 = "world" var str = str1 + str2
var str2 = "\(str1) hwc and the \(str2)" //hello hwc and the world
str.uppercaseString //HELLO WORLD str.lowercaseString //hello world
var str = "hello hwc" str.hasPrefix("hello") //true str.hasSuffix("123") //false
var str1 = "jack"
if str == str1{ println("Equal")}
Void insert(newElememt:Character,atIndex:String.index) //插入字符 Void removeAtIndex(i:String.Index) //删除字符 Void removeRange(subRange:Range<String.Index>)//删除一个区间 Void replaceRange(subRange:Range<String.Index>,with:C)
var str = "hello world" str.stringByAppendingFormat("%d",4) //hello world4
10 utf8 utf16属性
str.utf8 //返回str的utf8表示的集合
str.utf16 //返回str的utf17表示的集合
扩展String
通过扩展swifr的类,可以提供新的方法而不改变原有的类。以下为几个扩展函数,分别扩展了
通过下标获得子字符串
以及substring的三个重载
extension String { subscript (r: Range<Int>) -> String { get { let subStart = advance(self.startIndex, r.startIndex, self.endIndex) let subEnd = advance(subStart, r.endIndex - r.startIndex, self.endIndex) return self.substringWithRange(Range(start: subStart, end: subEnd)) } } func substring(from: Int) -> String { let end = countElements(self) return self[from..<end] } func substring(from: Int, length: Int) -> String { let end = from + length return self[from..<end] } func substring(from:Int, to:Int) ->String { return self[from..<to] } } var str = "hello world" var str1 = str.substring(6) var str2 = str.substring(0,to:5) var str3 = str.substring(0,length:5)在playground的右边输出可以看到
输出
hello
hello
world