码迷,mamicode.com
首页 > 编程语言 > 详细

Swift 字符串常用方法

时间:2017-10-16 19:26:28      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:int   count   doc   拼接   hello   with   seq   rac   substring   

        //字符串的定义
        var string = "Hello,swift";
        let string1 = "hello,swift";
        let string3 = "";
        let string4 = string;
        print(string);
        print(string.uppercased());// 大写
        print(string.lowercased());//小写
        //字符串字节
        let leng = string.lengthOfBytes(using: String.Encoding.utf8);
        print(leng);
        //获取字符串长度
        let leng2 = string1.characters.count;
        print(leng2,string3.characters.count,string4.characters.count);
        //字符串遍历
        for char in string1.characters{
            print(char);
        }
        //字符串拼接
        string += "liping";
        print(string);
        let str5 = string3 + string;
        print("str5=",str5);
        let str6 = [NSString .localizedStringWithFormat("%@,%@,%@","你好","开发","请善待")];
        print(str6)
        //追加字符
        string.append("!")
        print(string);
        //字符串截取
        let subStr = (string as NSString).substring(with: NSMakeRange(1, 6));
        let subStr2 = (string as NSString).substring(from: 5);
        let subStr3 = (string as NSString).substring(to: 5);
        print("subStr=",subStr,"subStr2=",subStr2,"subStr3=",subStr3)
        //字符串比较
        let s1:NSString = "你好,swift"
        let s2:NSString = "你好,李平";
        if s1.isEqual(to: s2 as String) {
            print("s1=s2");
        }else{
            print("s1!=s2");
        }
        //比较字符串的前缀后缀
        let array = ["do.docx","good.docx","name.docx","data.json","good.json"];
        for arrStr in array{
            if arrStr.hasPrefix("good") {
                print("前缀为good:\(arrStr)");
            }
            if arrStr.hasSuffix(".json") {
                print("后缀为.json:\(arrStr)");
            }
        }
        //字符串查找
        let s3:NSString = "swift";
        if (s1 as NSString).contains(s3 as String) {
            print("s1里面存在s3");
        }else{
            print("不存在");
        }
        //数字化字符串
        let s4 = "789";
        print("数字化:\((s4 as NSString).intValue)");

Swift 字符串常用方法

标签:int   count   doc   拼接   hello   with   seq   rac   substring   

原文地址:http://www.cnblogs.com/laolitou-ping/p/7678155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!