Swift 字符串常用方法

        //字符串的定义
        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)");

详细代码查看:https://github.com/xiaolitou-ping/Swift-All

posted @ 2017-10-16 18:12  朝阳向日葵  阅读(4118)  评论(0编辑  收藏  举报