swift-字符和字符串
-
OC定义字符:
char charValue = 'a';
-
swift定义字符:
var charValue : Character = "a"
-
Unicode 国际标准的文本编码,他几乎可以表示所有国家的字符、
OC可以存储ASCII字符,swift可以存ASCII+Unicodevar charValue :Character = "🐶" //正确的 var charValue2:Character = "小玉" //正确的 var charValue3:Character = "玉" //错误的 字符串是可以存很多字符的集合。 OC:NSString * stringValue = @"小玉"; swift:let stringValue:String = "小玉" 区别:NSString/String @""/"" //String -> NSString let string:NSString = NSString(string: "dahuan") OC是以‘\0’为字符串结束:NSString * stringValue = @"aaaa\0bbbb"; swift不是以'\0'结束:let stringValue:String = "aaaa\0bbbb"
-
字符串的常用方法
-
1、初始化空字符串
let emptyString = "" let emptyString2 = String()
-
2、遍历字符串
let string2 = "康姐是我们的好朋友!" for a in string2.characters { print(a) }
-
3、获取字符串的长度
let count = string2.characters.count print(count)
-
4、判断字符串是否为空
let emptyStr = "1" if emptyStr.isEmpty { print("yes") }
-
5、字符串的拼接
let str1 = "康姐" let str2 = "是我们的好朋友!" let result = str1 + str2 var str3 = "haha" str3 = str3 + str2 print(str3)
-
6、格式化字符串
let intValue = 10 let str4 = "爱情" let str5 = "\(intValue)、因为\(str4),不会悲伤" print(str5) //取小数后两位 let pi = 3.1415 let str6 = String(format: "%.2f", pi) print(str6)
-
7、字符串比较
//和C语言strcmp一样 let str7 = "a" let str8 = "ab" if str7 > str8 { print(">") } else if str7 < str8 { print("<") }
-
8、是否有前后缀
let str9 = "www.baidu.com" if str9.hasPrefix("www") { print("yes") } else { print("no") } if str9.hasSuffix("cm") { print("yes") } else { print("no") }
-
9、大小写
let str10 = str9.uppercaseString let str11 = str9.lowercaseString print(str10)
-
10、String转基本数据类型
let str12 = "5.2吗" let num = Float(str12) print(num)
-
11、截取字符串
let str13 = "康姐是我们的好朋友!" //str13.startIndex 从0开始 Index不是int let fromStr = str13.startIndex.advancedBy(2) let toStr = str13.endIndex.advancedBy(-2) let str14 = str13.substringFromIndex(toStr) let range:Range <String.Index> = Range(start: fromStr, end: toStr) let str15 = str13.substringWithRange(range) print(str15) let toStr1 = (str13 as NSString).substringToIndex(2); print(toStr1) let range1 = NSRange(location: 2, length: 6) let toStr2 = (str13 as NSString).substringWithRange(range1) print(toStr2)
-
您的资助是我最大的动力!
金额随意,欢迎来赏!