美文网首页
2019-05-05: 四:Swift中字符串的使用?

2019-05-05: 四:Swift中字符串的使用?

作者: 9801525d260a | 来源:发表于2019-05-05 23:39 被阅读0次

    一:Swift中字符串的使用?

    import UIKit
    
    // 定义字符串
    let string = "Hello World"
    
    let string1 : String
    string1 = "Hello"
    
    
    // 字符串的遍历
    for c in string1.characters {
        print(c)
    }
    
    // 字符串的拼接
    // 1.两个字符串之间的拼接
    let str1 = "my name"
    let str2 = " is why"
    let str3 = str1 + str2
    
    // 2.字符串和其他类型的拼接
    let age = 18
    let name = "why"
    let height = 1.88
    
    // 如果字符串中出现了变量:\(标识符的名称)
    let info = "My name is \(name), age is \(age), height is \(height)"
    
    // 3.字符串的格式化
    // 03:04
    let min = 3
    let second = 4
    var time = "\(min):\(second)"
    time = String(format: "%02d:%02d", arguments: [min, second])
    
    // 4.1字符串的截取一
    let url = "www.baidu.com"
    
    let url1 = (url as NSString).substringToIndex(3)
    let url2 = (url as NSString).substringFromIndex(10)
    let range = NSRange(location: 4, length: 5)
    let url3 = (url as NSString).substringWithRange(range)
    
    // 4.2:swift截取方式二
    
    // 1.定义字符串
    let str = "www.520it.com"
    
    // 2.截取开始位置
    let fromIndex = str.startIndex.advancedBy(3)
    let header = str.substringFromIndex(fromIndex)
    
    // 3.截取结束位置
    let toIndex = str.endIndex.advancedBy(-3)
    let footer = str.substringToIndex(toIndex)
    
    // 4.截取中间的字符串
    let range = Range(start: str.startIndex.advancedBy(4), end: str.endIndex.advancedBy(-4))
    let middle = str.substringWithRange(range)
    
    
    
    

    相关文章

      网友评论

          本文标题:2019-05-05: 四:Swift中字符串的使用?

          本文链接:https://www.haomeiwen.com/subject/yhfloqtx.html