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.
String
has builtin substring feature:
extension String : Sliceable {
subscript (subRange: Range) -> String { get }
}
If what you want is "going to the first index of a character", you can get the substring using builtin find()
function:
var str = "www.stackexchange.com"
str[str.startIndex ..< find(str, ".")!] // -> "www"
To find last index, we can implement findLast()
.
/// Returns the last index where `value` appears in `domain` or `nil` if
/// `value` is not found.
///
/// Complexity: O(\ `countElements(domain)`\ )
func findLast(domain: C, value: C.Generator.Element) -> C.Index? {
var last:C.Index? = nil
for i in domain.startIndex..
ADDED:
Maybe, BidirectionalIndexType
specialized version of findLast
is faster:
func findLast(domain: C, value: C.Generator.Element) -> C.Index? {
for i in lazy(domain.startIndex ..< domain.endIndex).reverse() {
if domain[i] == value {
return i
}
}
return nil
}