在Swift String中查找字符索引

现在该承认失败了...


在Objective-C中,我可以使用类似以下内容的东西:


NSString* str = @"abcdefghi";

[str rangeOfString:@"c"].location; // 2

在Swift中,我看到了类似的内容:


var str = "abcdefghi"

str.rangeOfString("c").startIndex

...但这只是给我一个String.Index,我可以用它下标回到原始字符串,但不能从中提取位置。


FWIW,其中String.Index有一个私有ivar _position,其中具有正确的值。我只是看不到它的暴露方式。


我知道自己可以轻松地将其添加到String中。我对这个新API中缺少的东西感到好奇。


动漫人物
浏览 1058回答 3
3回答

繁星淼淼

extension String {&nbsp; &nbsp; // MARK: - sub String&nbsp; &nbsp; func substringToIndex(index:Int) -> String {&nbsp; &nbsp; &nbsp; &nbsp; return self.substringToIndex(advance(self.startIndex, index))&nbsp; &nbsp; }&nbsp; &nbsp; func substringFromIndex(index:Int) -> String {&nbsp; &nbsp; &nbsp; &nbsp; return self.substringFromIndex(advance(self.startIndex, index))&nbsp; &nbsp; }&nbsp; &nbsp; func substringWithRange(range:Range<Int>) -> String {&nbsp; &nbsp; &nbsp; &nbsp; let start = advance(self.startIndex, range.startIndex)&nbsp; &nbsp; &nbsp; &nbsp; let end = advance(self.startIndex, range.endIndex)&nbsp; &nbsp; &nbsp; &nbsp; return self.substringWithRange(start..<end)&nbsp; &nbsp; }&nbsp; &nbsp; subscript(index:Int) -> Character{&nbsp; &nbsp; &nbsp; &nbsp; return self[advance(self.startIndex, index)]&nbsp; &nbsp; }&nbsp; &nbsp; subscript(range:Range<Int>) -> String {&nbsp; &nbsp; &nbsp; &nbsp; let start = advance(self.startIndex, range.startIndex)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let end = advance(self.startIndex, range.endIndex)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self[start..<end]&nbsp; &nbsp; }&nbsp; &nbsp; // MARK: - replace&nbsp; &nbsp; func replaceCharactersInRange(range:Range<Int>, withString: String!) -> String {&nbsp; &nbsp; &nbsp; &nbsp; var result:NSMutableString = NSMutableString(string: self)&nbsp; &nbsp; &nbsp; &nbsp; result.replaceCharactersInRange(NSRange(range), withString: withString)&nbsp; &nbsp; &nbsp; &nbsp; return result&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP