博客> Swift--字符串
Swift--字符串
2017-09-22 20:50 评论:1 阅读:352 上官尘
swift NSString
  1. 一 定义字符串

    oc语言: NSString *stringValue = "ab";

    swift语言:var stringValue1 = "ab"

    注: oc语言的字符只包含ascii码,每个字符只占1个字节,字符串是以\0结尾

            swift语言包含unicode字符集,  

二 字符串的使用

计算字符串长度:

OC: NSString *stringValue = @"abc李"; NSLog(@"%tu", stringValue.length);

swift: var stringValue = "abc李" print(stringValue.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))

字符串拼接

OC: NSMutableString str1 = [NSMutableString stringWithString:@"abc"]; NSString str2 = @"bcd"; [str1 appendString:str2]; NSLog(@"%@", str1);

swift: var str1 = "abc";

var str2 = "lnj"; var str = str1 + str2; print(str)

插入字符串

OC: NSInteger index = 1; NSString *str1 = [NSMutableString stringWithFormat:@"http://baidu/pic/%tu.png", index]; NSLog(@"%@", str1);

swift: var index = 1 var str3 = "http://www.520it.com/pic/\(index).png" print(str3)

字符串比较:

NSString str1 = @"abc"; NSString str2 = @"abc"; if ([str1 compare:str2] == NSOrderedSame){ NSLog(@"相等"); }else{ NSLog(@"不相等"); }

if ([str1 isEqualToString:str2]){ NSLog(@"相等"); }else{ NSLog(@"不相等"); }

swift: var str4 = "abc"; var str5 = "abc"; if str4 == str5{ print("相等"); }else{ print("不相等"); }

var str6 = "abd"; var str7 = "abc"; if str6 >= str7{ print("大于等于"); }else{ print("不大于等于"); }

判断前后缀

OC: NSString *str = @"http://baidu.com"; if ([str hasPrefix:@"http"]) { NSLog(@"是url"); } if ([str hasSuffix:@".com"]) { NSLog(@"是个什么鸟"); }

swift: var str8 = "http://www.520it.com" if str8.hasPrefix("http") { print("是url"); }

if str8.hasSuffix(".com") { print("是商用网站"); }

大小写转换 OC:

NSString *str = @"abc.txt"; NSLog(@"%@", [str uppercaseString]); NSLog(@"%@", [str lowercaseString]);

swift: var str9 = "abc.txt"; print(str9.uppercaseString) print(str9.lowercaseString)

转换为基本数据类型

OC: NSString *str = @"250"; NSInteger number = [str integerValue]; NSLog(@"%tu", number);

swift: var str10 = "250" var number:Int? = Int(str10)//如果没有整数,就反悔nil if number != nil { print(number!) }

收藏
1
sina weixin mail 回到顶部