Swfit 字符与字符串

Swfit 字符与字符串


OC 定义字符 char charValue = 'a';
Swift 定义字符 var charValue:Character = "a"
Unicode 国际标准的文本编码 他几乎可以表示所有国家字符
OC可以存储ASCII字符 Swift可以存ASCII+Unicode

var charValue:Character = "🐶"
var charValue2:Character = "旭"
//var charValue3:Character = "旭旭"  错误 字符!!!

print(charValue)
print(charValue2)

字符串是可以存很多字符的集合

OC NSString * str = @"旭旭";
Swift let str:String = "旭旭"

OC -> @""
Swift -> ""

String -> NSString (Swift->OC)
let str:NSString = NSString(string:"旭旭")

OC 以\0为结束
Swift 不是以\0为结束

字符串的常用方法

初始化字符串

let emptyString = ""
let emptyString2 = String()

遍历字符串

let string = "lalala"
for a in string.characters{
    print(a)
}

获取字符串的长度

let count = string.characters.count
print(count)

判断字符串是否为空

let emptyStr = ""
if emptyStr.isEmpty{
    print("YES")
}

字符串的拼接

let str1 = "lala"
let str2 = "kaka"
let result = str1 + str2
print(result)

格式化字符串

let str1 = "爱"
let str2 = "旭宝\(str1)吃鱼"
print(str2)

取小数后两位

let pi = 3.141592653
let str = String(format: "%.2f",pi)
print(str)

字符串比较

let str1 = "abc"
let str2 = "abc"
if str1 == str2 {
    print("相等")
}

查询前后缀

let str = "www.baidu.com"
if str.hasPrefix("www"){
    
}
if str.hasSuffix("com"){
    
}

大小写

let str = "www.baidu.com"
let str1 = str.uppercaseString
let str2 = str.lowercaseString
print(str1)
print(str2)

String转基本数据类型

//输出为可选类型 因为有可能不成功
let str = "5.2"
let num = Float(str12)
print(num)

截取字符串

let str = "qwertyuiop"
let toStr = str.startIndex.advancedBy(2) //从0开始跑
let str1 = str.substringToIndex(toStr)
print(str1)
let str = "qwertyuiop"
let toStr = str.endIndex.advancedBy(-2)
let str1 = str.substringToIndex(toStr)
print(str1)

let str = "qwertyuiop"
let fromStr = str.startIndex.advancedBy(2)
let toStr = str.endIndex.advancedBy(-2)
let range:Range <String.Index> = Range(start:fromStr,end:toStr)//swift 3废弃
let str1 = str.substringWithRange(range)
print(str1)
let str = "qwertyuiop"
let toStr = (str as NSString).substringToIndex(2)
print(toStr)
let str = "qwertyuiop"
let  range = NSRange(location: 2,length: 5)
let  toStr = (str as NSString).substringWithRange(range)
print(toStr)
posted @ 2016-05-22 09:18  旭宝爱吃鱼  阅读(475)  评论(0编辑  收藏  举报