LaneBlog

蝼蚁虽小,也有梦想

PHP Socket服务 | PHP微信开发框架 | 开源博客

初探Swift二 - 字符串

Clicks: 5495 Date: 2015-01-07 13:34:17 Power By 李轩Lane

swift ios

    

    初探Swift之Swift字符串、字符串处理、字符串函数。Swift字符串本质是一个对象,同其他语言一样,可以使用拼接、长度、子字符串查找、子字符串替换、子字符串删除等操作。


//字符串长度,长度为5

var str_es = "swift"

countElements(str_es)

//中文字符串长度,长度为2,一个汉子为1

var str_ch = "你好"

countElements(str_ch)


//声明一个字符

let myChar:Character = "!"


//比较,同其他语言,是按照字典的顺序。与长度无关

let a = "abcd";

let b = "abd";

a == b

a > b

a < b


//字符串的前缀和后缀

let chapterNames = [

    "第一:1111",

    "第二:1111",

    "第二:1111a",

    "第二:1111",

    "第三:1111",

    "第三:1111a",

]

//前缀为第二的个数统计

var count = 0

for name in chapterNames{

    if name.hasPrefix("第二"){

        count++

    }

}

count

//后缀为“a”的个数统计

count = 0

for name in chapterNames{

    if name.hasSuffix("a"){

        count++

    }

}

count




//字符串高级操作,需要引入Foundation

import Foundation


var str = "hello WOrld";

//首字母大写

str.capitalizedString

//大写

str.uppercaseString

//小写

str.lowercaseString


//去除两边的空格

var str2 = "  hi ! "

str2.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())


//字符串按照空格分割为数组,同php的explode函数

var str3 = "hello world"

str3.componentsSeparatedByString(" ")


//数组连接为字符串,同php的implode函数

var str4 = "_"

str4.join(["1","2","3"])


//查找字符串

var str = "Welcome to play Swift! Step by Step learn Swift language from now!"

str.rangeOfString("Step")

//第二个参数是枚举,可以根据Xcode的提示看到,NSStringCompareOptions.CaseInsensitiveSearch是不区分大小写

str.rangeOfString("welcome", options: NSStringCompareOptions.CaseInsensitiveSearch)


//字符串的开头位置

str.startIndex

//字符串的结束为止

str.endIndex


//Range

let strRange = Range<String.Index>(start:str.startIndex, end:str.endIndex)

//在Range范围内查找

let startIndex = str.startIndex

let endIndex:String.Index = advance(str.startIndex, 10)

let searchRange = Range<String.Index>(start:startIndex, end:endIndex)

str.rangeOfString("Step", options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange)

//截取开头的4个字符

var toIndex = advance(str.startIndex, 4)

str.substringToIndex(toIndex)

©2014 www.lanecn.com , All rights reserved. Power By Li Xuan.  京ICP备14005030号