美文网首页swift开发技巧
iOS Swift中String的常用操作以及数据转化

iOS Swift中String的常用操作以及数据转化

作者: 逍遥晨旭 | 来源:发表于2017-05-17 10:29 被阅读56次

    一、String的常用操作

    1、字符和字符串的定义
    //常量字符串
    let a = "james"
    //变量字符串
    var b = "wade"
    b = "Paul"
    //声明为nil的字符串
    var c:String?
    //空字符串(不提倡)
    let d = String()
    //空字符串,提倡用这样的字面量语法声明,类型可不指定,swift自动识别
    var e = ""
    
    2、判断字符串
    //1、判断字符串是否为空
    let e = "james"
    let bl2:Bool = e.isEmpty
    NSLog("The shoppingList firstItem %@", bl2 ? "YES" : "NO")
    
    let e = "我是James的粉丝,还喜欢韦德"
    //2、判断在字符串中包含某个字符(只能是一个)
    if let index3 = e.characters.index(of: "韦"){
        //包含“韦”字符
        print("The value for index3 was \(index3).")
    }
    //3、判断在字符串中包含某个子字符串
    if let range4 = e.range(of: "James"){
        //包含某个子字符串"James"
        print("The value for range4 was \(range4).")
    }
    //4、是否含有前缀
    let bool1:Bool = e.hasPrefix("我是")  
    //5、是否含有后缀
    let bool2:Bool = e.hasSuffix("喜欢") 
    print("The Prefix value for e was \(bool1).The Suffix value for e was \(bool2).")
    
    3、 拼接和添加字符串
    let str1 = "James,"
    let str2 = "你好"
    let str3 = "!"
    //方法1:
    var p_str1 = str1 + str2
    //方法2:
    var p_str2 = String(format:"%@ %@",str1,str2)
    let p_str3 = String(format:"%@ %@ %@",str1,str2,str3)
    //方法3:
    let p_str4 = "霸气的 \(str1)\(str2)\(str3)"
    print("The p_str1 value is \(p_str1);The p_str2 value is \(p_str2);The p_str3 value is\(p_str3);The p_str4 value is \(p_str4);")
    
    //在后面添加字符/字符串
    p_str1.append(str3)
    //+=:用于在后面添加同类型的
    p_str2 += str3
    print("The new p_str1 value is \(p_str1);The new p_str2 value is \(p_str2);")
    
    4、字符计数及字符串索引
    //1、计算字符的个数
    let wade = "holle wade"
    let longth = wade.characters.count
    print("The length of the str was \(longth).")
    //2、字符串索引
    //        wade.startIndex    //返回0
    //        wade.endIndex      //最后一个字符串的下一个位置
    print("wade startIndex was \(wade.startIndex).wade endIndex was \(wade.endIndex).")
    
    //3、用字符串的字符数组的index(after:Index)或index(before:Index)引用Index后一个或前一个索引,来获取对应的元素
    let after = wade[wade.characters.index(after: wade.startIndex)]  //b
    let before = wade[wade.characters.index(before: wade.endIndex)]   //f
    print("after was \(after).before was \(before).")
    
    //4、索引3的元素
    let index = wade.index(wade.startIndex,offsetBy:3)    //起始位置,偏移位
    print("index was \(index).")
    //5、确定index1的值是安全的,是否越界
    let index1 = wade.index(wade.startIndex,offsetBy:3, limitedBy:wade.endIndex) //起始位置,偏移位,最后一个字符串的下一个位置
    print("index was \(String(describing: index1)).")
    
    5、插入字符或字符串
    var StrinsertStr = "James很伟大"
    //1、在开头插入一个字符,注意是字符不是字符串
    StrinsertStr.insert("@", at: StrinsertStr.startIndex)
    //2、在指定位置插入一个字符
    StrinsertStr.insert("@", at: StrinsertStr.index(StrinsertStr.startIndex, offsetBy: 6))
    print("insertStr was \(StrinsertStr)).")
    
    //3、在开头字符的后面插入一个字符串
    StrinsertStr.insert(contentsOf:"伟大的".characters, at: StrinsertStr.index(after: StrinsertStr.startIndex))    
    //4、在结尾字符的前面插入一个字符串
    StrinsertStr.insert(contentsOf:",OK?".characters, at: StrinsertStr.index(before: StrinsertStr.endIndex)) 
    //5、在指定位置插入一个字符串
    var p_str5 = "interesting"
    StrinsertStr.insert(contentsOf:p_str5.characters, at: StrinsertStr.endIndex)    
    StrinsertStr.insert(contentsOf: ["~","~","~"], at: StrinsertStr.index(StrinsertStr.startIndex, offsetBy: 12))  
    print("insertStr was \(StrinsertStr)).")
    
    6、截取字符串
    var ceptionStr = "勒布朗·詹姆斯一共获得了4个常规赛MVP"
    //通过索引截取字符串
    //从开头截取指定的长度
    let preStr = String(ceptionStr.characters.prefix(3))
    //从末尾截取指定的最大长度。
    let sufStr = String(ceptionStr.characters.suffix(3))
    //如果最大长度超过集合中元素的数目,则结果包含集合中的所有元素
    let allStr = String(ceptionStr.characters.prefix(50))
    print("preStr was \(preStr)。sufStr was \(sufStr)。allStr was \(allStr)")
    //offsetBy:最大为endIndex  
    let i = ceptionStr.index(ceptionStr.startIndex, offsetBy: 4)
    let j = ceptionStr.index(ceptionStr.startIndex, offsetBy: 7)
    
    //substring(to:):从开头截取到指定的索引,不包含索引所在元素。
    var ceptionStr1 = ceptionStr.substring(to: i)
    print("ceptionStr1 was \(ceptionStr1)。")
    //从指定的索引开始截取到末尾,包含索引所在元素。
    ceptionStr1 = ceptionStr.substring(from: i)
    print("ceptionStr2 was \(ceptionStr1)。")
    //substring(with:):包含指定的索引区间
    ceptionStr1 = ceptionStr.substring(with: i..<j)
    print("ceptionStr3 was \(ceptionStr1)。")
    
    let range1 = ceptionStr.range(of: "勒布朗")
    let range2 = ceptionStr.range(of: "常规赛MVP")
    //截取range1之后的值
    ceptionStr1 = ceptionStr.substring(from: (range1?.upperBound)!)
    print("ceptionStr4 was \(ceptionStr1)。")
    //截取range1与range2直接的值
    ceptionStr1 = ceptionStr.substring(with: (range1?.upperBound)!..<(range2?.lowerBound)!)
    print("ceptionStr5 was \(ceptionStr1)。")
    
    //通过指定字符串截取子串
    // 正向检索,从前到后找到第一个 "很" 字符的range
    var range = ceptionStr.range(of: "勒布朗")
    //反向检索
    //options: 用来指定一个选项标记(这个标记可以作为搜索的条件), .backwards:反向检索
    range = ceptionStr.range(of: "4个", options: .backwards)
    //range: 设置搜索的范围
    //locale: 可以语言环境
    range = ceptionStr.range(of: "4个", options: .backwards, range: nil, locale: nil)
    ceptionStr1 = ceptionStr.substring(with: (range?.lowerBound)!..<(range2?.lowerBound)!)
    print("ceptionStr6 was \(ceptionStr1)。")
    
    7、替换字符串
    let ceptionIndex = ceptionStr.characters.index(of: "4")
    let offsetIndex = ceptionStr.index(ceptionIndex!, offsetBy: 1)
    ceptionStr.replaceSubrange(ceptionIndex! ..< offsetIndex, with: "3")
    //方法1:
    let ceptionIndex2 = ceptionStr.characters.index(of: "常")
    let offsetIndex2 = ceptionStr.index(ceptionIndex2!, offsetBy: 1)
    ceptionStr.replaceSubrange(ceptionIndex2! ..< offsetIndex2, with: "季后")
    
    // //方法1:(简易写法)
    let range3 = ceptionStr.range(of: "常")
    ceptionStr.replaceSubrange(range3!, with: "季后")
    print("ceptionStr was \(ceptionStr)。")
    
    8、删除字符串
    var deleteStr = "勒布朗·詹姆斯(LeBron James)美国职业篮球运动员,司职小前锋,绰号“小皇帝”,效力于NBA克利夫兰骑士队。"
    let x = deleteStr.index(deleteStr.startIndex, offsetBy: 8)
    //1、在指定位置删除一个字符
    deleteStr.remove(at: x)
    print("deleteStr1 was \(deleteStr)。")
    deleteStr.remove(at: deleteStr.startIndex)
    print("deleteStr2 was \(deleteStr)。")
    deleteStr.remove(at: deleteStr.index(after: deleteStr.startIndex))
    print("deleteStr3 was \(deleteStr)。")
    deleteStr.remove(at: deleteStr.index(before: deleteStr.endIndex))
    print("deleteStr4 was \(deleteStr)。")
    
    var originalStr = "勒布朗·詹姆斯(LeBron James)是美国职业篮球运动员,司职小前锋,绰号“小皇帝”,效力于NBA克利夫兰骑士队。"
    //2、删除指定范围的字符
    let ran1 = originalStr.range(of: "(LeBron James)")
    originalStr.removeSubrange(ran1!)
    print("originalStr2 was \(originalStr)。")
    
    9、遍历字符串
    let str = "variable"
    //方法1
    for word in str.characters {
        print(word)
    }
    //方法2
    str.characters.forEach{print($0)}
    //方法3
    for (index3,value) in str.characters.enumerated() {
        print("\(index3) \(value)")
    }
    
    10、字符串的比较
    let compareStr1 = "bei jing"
    let compareStr2 = "BEI JING"
    
    // 判读两个字符串是否相等
    let bl3:Bool = str1 == str2
    print("bl3的值\(bl3)")
    // 比较两个字符串
    let result1 = compareStr1.compare(compareStr2)
    print(result1)
    // 忽略大小写比较
    let result2 = compareStr1.caseInsensitiveCompare(compareStr2)
    print(result2)
    

    二、字符串的转换

    1、大小写字母转换
    //1、转换为大写
    var capitalStr = "LeBron James"
    capitalStr = capitalStr.uppercased()
    print("capitalStr was \(capitalStr)。")
    //2、转换为小写
    capitalStr = capitalStr.lowercased()
    print("capitalStr2 was \(capitalStr)。")
    
    2、字符串与数组的转换
    var strArray = ["hello", "LeBron James", "2017"]
    //数组通过指定字符拼接
    let array_str1 = strArray.joined(separator: "-")
    print("array_str1 was \(array_str1)。")
    //拆分为数组
    strArray = array_str1.components(separatedBy: "-")
    print("strArray was \(strArray)。")
    
    3、NSString和String类型转换
    let Str1 = "LeBron James"
    //定义NSString,String->NSString
    let Str2 = NSString(string: Str1)
    print("Str1 was \(Str1)。Str2 was \(Str2),Str2的类型\(type(of:Str2)),Str1的类型\(type(of:Str1))")
    
    //定义NSString,NSString -> String
    let Str3:NSString = Str1 as NSString
    let Str4 = Str3 as String    //类型推导,:String可省略
    
    print("Str3的类型\(type(of:Str3)),Str4的类型\(type(of:Str4))")
    
    4、字符串转数值
    let string = "30"
    print(string)
    let nStr = string as NSString // 借用NSString输出
    print(nStr)
    
    print("doubleValue:\(nStr.doubleValue)")
    print("floatValue:\(nStr.floatValue)")
    print("intValue:\(nStr.intValue)")
    print("integerValue:\(nStr.integerValue)")
    print("longLongValue:\(nStr.longLongValue)")
    print("boolValue:\(nStr.boolValue)")
    

    三、NSString和SwiftString的区别

    1、String类型是值类型,NSString是引用类型
    * NSString初始化了一个指针指向了这个字符串,但Swift的String是把字符串字面量赋值给变量。
    *即:声明创建后的对象NSString获得的是指向NSString类型的地址,而string获得的是一个值。
    2、Swift的String字符串之间的拼接比NSString方便
    NSString需要用append或者stringWithFormat将两个字符串拼接;而Swift的String只需要用 “+” 即可
    3、Swift的String 可以实现字符串遍历
    4、Swift的String独有的字符串插入字符功能
    

    NSString和SwiftString的区别可以参看这篇文章

    相关文章

      网友评论

        本文标题:iOS Swift中String的常用操作以及数据转化

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