本文介绍了Swift:如何从字符的开头到最后一个索引获取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想学习将字符串转换为另一个字符串的最佳/最简单方法,但只有一个子集,从头开始并转到字符的最后一个索引。I want to learn the best/simplest way to turn a string into another string but with only a subset, starting at the beginning and going to the last index of a character.例如,将www.stackoverflow.com转换为www.stackoverflow。什么代码片段可以做到这一点,并且是最快速的? (我希望这不会带来争论,但我找不到关于如何在Swift中处理子串的好教训。For example, convert "www.stackoverflow.com" to "www.stackoverflow". What code snippet would do that, and being the most swift-like? (I hope this doesn't bring a debate, but I can't find good lesson on how to handle substrings in Swift.推荐答案 只是向后访问 最好的方法是使用 substringToIndex 组合到 endIndex property和 advance 全局函数。Just accessing backwardThe best way is to use substringToIndex combined to the endIndexproperty and the advance global function.var string1 = "www.stackoverflow.com"var index1 = advance(string1.endIndex, -4)var substring1 = string1.substringToIndex(index1) 寻找从后面开始的字符串 使用 rangeOfString 并将 options 设置为 .BackwardsSearch var string2 = "www.stackoverflow.com"var index2 = string2.rangeOfString(".", options: .BackwardsSearch)?.startIndexvar substring2 = string2.substringToIndex(index2!)没有扩展,纯粹的惯用语Swift No extensions, pure idiomatic Swift 提前现在是部分索引,称为 advancedBy 。你这样做:advance is now a part of Index and is called advancedBy. You do it like:var string1 = "www.stackoverflow.com"var index1 = string1.endIndex.advancedBy(-4)var substring1 = string1.substringToIndex(index1) Swift 3.0 您无法在字符串上调用 advancedBy 因为它有可变大小的元素。你必须使用 index(_,offsetBy :) 。var string1 = "www.stackoverflow.com"var index1 = string1.index(string1.endIndex, offsetBy: -4)var substring1 = string1.substring(to: index1)很多东西都已重命名。这些案例是用camelCase编写的, startIndex 成为 lowerBound 。A lot of things have been renamed. The cases are written in camelCase, startIndex became lowerBound.var string2 = "www.stackoverflow.com"var index2 = string2.range(of: ".", options: .backwards)?.lowerBoundvar substring2 = string2.substring(to: index2!) ,我不建议强行解包 index2 。您可以使用可选绑定或 map 。就个人而言,我更喜欢使用 map :Also, I wouldn't recommend force unwrapping index2. You can use optional binding or map. Personally, I prefer using map:var substring3 = index2.map(string2.substring(to:)) Swift 4 Swift 3版本仍然有效但现在您现在可以使用索引范围的下标:Swift 4The Swift 3 version is still valid but now you can now use subscripts with indexes ranges:let string1 = "www.stackoverflow.com"let index1 = string1.index(string1.endIndex, offsetBy: -4)let substring1 = string1[..<index1]第二种方法保持不变:let string2 = "www.stackoverflow.com"let index2 = string2.range(of: ".", options: .backwards)?.lowerBoundlet substring3 = index2.map(string2.substring(to:)) 这篇关于Swift:如何从字符的开头到最后一个索引获取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-27 09:41