string

1.初始化空字符串 

var emptyString = ""// 空字符串字面量 
var anotherEmptyString = String() // 初始化方法
// 两个字符串均为空并等价。

if emptyString.isEmpty {
    print("Nothing to see here")
}

2.字符串拼接

//两个字符串的拼接
let str1 = "Hello"
let str2 = "World"
let str3 = str1 + str2

//字符串和其他数据类型的拼接
let name = "why"
let age = 18

let info = "my name is \(name), age is \(age)"

//字符串的格式化
//比如时间:03:04
let min = 3
let second = 4

let time = String(format: "%02d:%02d", arguments: [min, second])

3.遍历

for c in "abc".characters {
    print(c)
}

4.字符串的截取,使用NSString

let myStr = "www.baidu.com"
var subStr = (myStr as NSString).substring(from: 4)
subStr = (myStr as NSString).substring(to: 3)
subStr = (myStr as NSString).substring(with: NSRange(location: 4, length: 5))

使用String

var sub = myStr.substring(from: myStr.index(myStr.startIndex, offsetBy: 4))
//sub = myStr.substring(with: <#T##Range<String.Index>#>)
myStr.substring(to: myStr.index(myStr.startIndex, offsetBy: 3))

5.插入,比较,开头,结尾

var welcome = "hello"
        //用于:插入字符c
        welcome.insert("!", at: welcome.endIndex) // welcome 变量现在等于 "hello!"
        //用于:插入字符串
        welcome.insert(contentsOf:" there".characters, at: welcome.index(before: welcome.endIndex)) // welcome 变量现在等于 "hello there!"
        welcome.remove(at: welcome.index(before: welcome.endIndex)) // welcome 现在等于 "hello there"
        let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
        welcome.removeSubrange(range)
        
        // welcome 现在等于 "hello"
        
        //2.比较字符串(==  / !=)
        if greeting == welcome {
            
        }
        
        //3.前缀/后缀相等
        if greeting.hasPrefix("http") {
            print("以什么开头")
        }
        
        if greeting.hasSuffix("com") {
            print("以什么结尾")
        }

6.大小写

let myStr = "www.baidu.com"
//首字母大写
myStr.capitalized(with: Locale.current)
//大写
myStr.uppercased()
//小写
myStr.lowercased()
//字符串长度

  myStr.characters.count

 7.编码,转码

var strURL=String(format:"中123")
//编码
var cs=NSCharacterSet(charactersIn:"`#%^{}\"[]|\\<>//").inverted
//使用NSCharacterSet(charactersIn:"`#%^{}\"[]|\\<>//").inverted与NSCharacterSet.alphanumerics结果一致
strURL = strURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.alphanumerics)!
//解码
strURL = strURL.removingPercentEncoding!

 8.C 语言字符串 -> string

String(cString: ivarName!)

 

posted @ 2017-03-27 17:56  ZJea  阅读(294)  评论(0编辑  收藏  举报