Swift - 16 - String.Index和Range

//: Playground - noun: a place where people can play

import UIKit

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

// range
str.rangeOfString("Step")   // 默认从前面开始搜索
str.rangeOfString("Step", options: NSStringCompareOptions.BackwardsSearch, range: nil, locale: nil) // 从后面开始搜索

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

// 搜索特定范围中特定字符串的范围
var searchStartIndex:String.Index = str.startIndex  // 搜索开始的位置
var searchEndIndex:String.Index = searchStartIndex.advancedBy(7)  // 搜索结束的位置
let searchRange = Range<String.Index>(start: searchStartIndex, end: searchEndIndex)
str.rangeOfString("Step", options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil)


// subString
var toIndex = str.startIndex.advancedBy(4)
str.substringToIndex(toIndex)

var fromIndex = str.startIndex.advancedBy(14)
str.substringFromIndex(fromIndex)

str.substringWithRange(searchRange)

// insert
var insertIndex = searchStartIndex.advancedBy(22)
str.insert("!", atIndex: insertIndex);

// remove
str.removeAtIndex(insertIndex)
str.removeRange(searchRange)

// replace
var replaceRange = Range<String.Index>(start: str.startIndex, end: str.startIndex.advancedBy(14))
str.stringByReplacingCharactersInRange(replaceRange, withString: "Rinpe Chan")


// String.Index 也是一种数据类型

  

posted @ 2015-12-16 12:33  Rinpe  阅读(790)  评论(0编辑  收藏  举报