在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Swift 的 注:Swift 的
1.字符串定义 var s = "abc" var s1:String = "abc"
// 两个字符串均为空并等价。 var emptyString = "" // 空字符串字面量 var anotherEmptyString = String() // 初始化 String 实例
字符串字面量可以包含以下特殊字符:
let wiseWords = "\"我是要成为海贼王的男人\" - 路飞" // "我是要成为海贼王的男人" - 路飞 let dollarSign = "\x24" // $, Unicode 标量 U+0024 let blackHeart = "\u2665" // ♥, Unicode 标量 U+2665 let sparklingHeart = "\U0001F496" // ????, Unicode 标量 U+1F496
2.字符串拼接 //字符串拼接 var x = "x" var y = "y" var z = x + y var m = z + "m" var n = "n" n += m //使用\()完成字符串的插值 var result = "\(x)==\(y)==\(z)==\(m)==\(n)" println(result)//结果:x==y==xy==xym==nxym //字符串与字符拼接 let s1 = "hello" let c1: Character = "!" let plus1 = s1 + c1 // 等于 "hello!" let plus2 = c1 + s1 // 等于 "!hello"
3.字符串遍历 var myString = "This is a string" for character in myString{ println(character) }
4.字符个数统计 var myString = "Here is my string, lets count the characters!" println(myString.characters.count)
5.字符串比较 & 是否包含前后缀 var check1:String = "Swift is good!" var check2:String = "Swift is good!" //字符串是否相等 if check1 == check2 { println("check1 = check2") } else { println("check1 != check2") } //是否包含前缀 var preCheck = "Swift" if check1.hasPrefix(preCheck) { println("包含前缀") } //是否包含后缀 var sufCheck = "good!" if check1.hasSuffix(sufCheck) { println("包含后缀") }
6.大小写转换 let myString = "Wait a moment, please." let newString = myString.uppercaseString //The string is now "WAIT A MOMENT, PLEASE." let myString = "Wait a moment, please." let newString = myString.lowercaseString // The string is now "wait a moment, please."
7.字符串是否包含其他字符串 var myString = "This is a string test" if myString.rangeOfString("string") { println("exists") }
8.字符串截取 //截取字符串的标识位从1开始计数 let myString = "ABCDEFGHI" //1.从目标标识位后一个字符开始截取余下的字符串 let mySubstring = (myString.substringFromIndex(2)) println(mySubstring) // "CDEFGHI" //2.从第一个字符截取到目标标识位 let mySubstring2 = (myString.substringToIndex(4)) println(mySubstring2) // "ABCD"
9.字符串去空格 var myString = " Let's trim the whitespace " var newString = myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
10.字符串分割为字符串数组 //单一分隔符:只有一种分割符 var myString = "Berlin, Paris, New York, San Francisco" //1.隐式定义字符串数组 var myArray = myString.componentsSeparatedByString(",") //2.显示定义字符串数组 var myArray2 : String[] = myString.componentsSeparatedByString(", ") for em in myArray2 { print(em) //Berlin Paris New York San } //多重分割符:有2个或两个以上分隔符 var myString2 = "One-Two-Three-1 2 3" var array2:String[] = myString2.componentsSeparatedByCharactersInSet(NSCharacterSet (charactersInString: "- ")) //["One", "Two", "Three", "1", "2", "3"]
11.字符串转换为NSData let myString = "String to encode" let string: NSString = myString let data = string.dataUsingEncoding(NSUTF8StringEncoding)
参考文章:http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/
|
请发表评论