专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Swift

从 Playgrounds 论 Swift(三): 字符串和字符(Strings and Characters)

发布时间:2011-06-30 07:29:29 文章来源:www.iduyao.cn 采编人员:星星草
从 Playgrounds 论 Swift(3): 字符串和字符(Strings and Characters)
转载请声明出处:http://blog.csdn.net/jinnchang/article/details/43225823

1、字符(Characters)

// 初始赋值
let yenSign: Character = "¥"

// 遍历字符串获取字符
for character in "Dog" {
    println(character)
}
// D
// o
// g

// 计算字符数量
println(countElements("Hello!"))

3、字符串(String)

字符串是值类型。
字符串和字符之间可通过(+)连接。

// 初始化空字符串
var emptyString = ""
var anotherEmptyString = String()

// 判断字符串是否为空
println(emptyString.isEmpty)
println(anotherEmptyString.isEmpty)

// 字符串可变性
var variableString = "Horse" 
variableString += " and carriage"

// 字符串的大写小写转换
let normal = "Could you help me, please?" 
println(normal.uppercaseString)
// prints “COULD YOU HELP ME, PLEASE?”
println(normal.lowercaseString)
// prints “could you help me, please?”
注意:不能将一个字符串或者字符添加到一个已经存在的字符变量上,因为字符变量只能包含一个字符。

4、比较字符串

// 比较字符串是否相等
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
}
// prints "These two strings are considered equal"

// 比较字符串前缀是否相等
let romeoAndJuliet = [
    "Act 1 Scene 1: Verona, A public place",
    "Act 1 Scene 2: Capulet's mansion",
    "Act 1 Scene 3: A room in Capulet's mansion",
    "Act 1 Scene 4: A street outside Capulet's mansion",
    "Act 1 Scene 5: The Great Hall in Capulet's mansion",
    "Act 2 Scene 1: Outside Capulet's mansion",
    "Act 2 Scene 2: Capulet's orchard",
    "Act 2 Scene 3: Outside Friar Lawrence's cell",
    "Act 2 Scene 4: A street in Verona",
    "Act 2 Scene 5: Capulet's mansion",
    "Act 2 Scene 6: Friar Lawrence's cell"
]
var act1SceneCount = 0
for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1 ") {
        ++act1SceneCount
    }
}
println("There are \(act1SceneCount) scenes in Act 1")
// prints "There are 5 scenes in Act 1"

// 比较字符串后缀是否相等
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
    if scene.hasSuffix("Capulet's mansion") {
        ++mansionCount
    } else if scene.hasSuffix("Friar Lawrence's cell") {
        ++cellCount
    }
}
println("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
// prints "6 mansion scenes; 2 cell scenes"

5、Unicode

Unicode 相关的此处省略,后续会专门开篇讲述。

6、结语

文章最后更新时间:2015年1月29日09:08:04。
欲了解更细致的请参考官方文档:Strings and Characters
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: