博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swift学习笔记 - 字符串
阅读量:6236 次
发布时间:2019-06-22

本文共 2314 字,大约阅读时间需要 7 分钟。

 

1. 不可变字符串

Objective-C:

NSString *string1 = @"Hello World!";

Swift:

let string1 = "Hello world!"

 

2. 可变字符串

Objective-C:

NSMutableString *string2 = [NSMutableString new];NSMutableString *string3 = [@"" mutableCopy];

Swift:

var string2 = String()var string3 = ""

 

3. 输出

Objective-C:

NSLog(@"%lu", (unsigned long)string1.length); // Prints "12"NSLog(@"%i", !string2.length);                 // Prints "1"NSLog(@"%i", [string1 hasPrefix:@"Hello"]); // Prints "1"NSLog(@"%i", [string1 hasSuffix:@"earth!"]);// Prints "0"

Swift:

println(string1.utf16Count)                // Prints "12"println(countElements(string1))            // Prints "12"println(string2.isEmpty)                // Prints "true"println(string1.hasPrefix("Hello"))     // Prints trueprintln(string1.hasSuffix("earth!"))     // Prints false

 

4. 比较

Objective-C:

// Prints "string2 equals string3"if ([string2 isEqualToString:string3]) {    NSLog(@"string2 equals string3");}

Swift:

// Prints "string2 equals string3"if string2 == string3 {    println("string2 equals string3")}

5. 转换

Objective-C:

NSString *fiveString = [@5 stringValue]; // "5"NSInteger five = [fiveString integerValue];

Swift:

let fiveString = "\(5)"                         // "5"let five = fiveString.toInt()!let pi = Double((π as NSString).doubleValue)     // 3.14

 

6. Copy and Mutable Copy

Objective-C:

NSMutableString *string4 = [string1 mutableCopy];[string4 appendFormat:@"Am I alone?"];NSLog(@"%@", string1);        // Prints "Hello world!"NSLog(@"%@", string4);        // Prints "Hello world! Am I alone?"NSMutableString *string5 = string4;[string5 replaceCharactersInRange:NSMakeRange(13, 10)    withString:@"How do you like me now"];// Prints "Hello world! How do you like me now?"if ([string4 isEqualToString:string5]) {    NSLog(@"%@", string5);}NSMutableString *tempHigh = [@"85" mutableCopy];NSMutableString *tempLow = [@"70" mutableCopy];NSString *degreeF = @"\u2109";[tempHigh appendString:degreeF];[tempLow appendString:degreeF];// Prints "High/Low: 85°F/70°F"NSLog(@"High/Low: %@/%@", tempHigh, tempLow);

Swift:

var string4 = string1string4 += " Am I alone?"println(string1)         // Prints "Hello world!"println(string4)         // Prints "Hello world! Am I alone?"var string5 = string4let startIndex = advance(string5.startIndex, 13)string5.replaceRange(startIndex..

 

转载地址:http://qakia.baihongyu.com/

你可能感兴趣的文章
SEM如何做数据分析?
查看>>
Word文档怎么在线压缩变小?
查看>>
语音转文字如何在线转换的?
查看>>
区块链教程Fabric1.0源代码分析policy(背书策略
查看>>
平台化,中台化
查看>>
比你优秀的人都在努力,你还有什么理由浑浑噩噩
查看>>
无线传输更安全也更稳定
查看>>
ABB焊接机器人伺服电机维修常见故障
查看>>
oracle使用plsql插入数据中文乱码问题
查看>>
ssh各种异常登陆
查看>>
nginx域名配置方法
查看>>
Java 基本问题
查看>>
马哥2016全新Linux+Python高端运维班第一周作业
查看>>
setup Docker private registry
查看>>
Redis 为什么使用单进程单线程方式也这么快
查看>>
JAVA's NIO, Netty And Mina文章推荐
查看>>
《Java从小白到大牛精简版》之第4章 Java语法基础
查看>>
启动文件类型与芯片容量大小区别
查看>>
Ez×××_over_asa
查看>>
聊聊CentOS6的启动过程
查看>>