1

I am trying to extract a partial String from a given input String in Swift5. Like the letters 2 to 5 of a String.

I was sure, something as simple as inputString[2...5]would be working, but I only got it working like this:

String(input[(input.index(input.startIndex, offsetBy: 2))..<(input.index(input.endIndex, offsetBy: -3))])

... which is still using relative positions (endIndex-3 instead of position #5)

Now I am wondering where exactly I messed up.

How do people usually extract "cde" from "abcdefgh" by absolute positions??

Kali
  • 25
  • 2
  • How about `let input = "abcdefghij"; let cde = String(input.prefix(5).dropFirst(2))`? – vacawama Jun 15 '19 at 22:08
  • That's just what I was looking for, thanks man! – Kali Jun 15 '19 at 22:39
  • @Kali https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language/38215613?r=SearchResults&s=1%7C48.9460#38215613 – Leo Dabus Jun 15 '19 at 22:47

1 Answers1

1

I wrote the following extension for shorthand substrings without having to deal with indexes and casting in my main code:

extension String {
    func substring(from: Int, to: Int) -> String {
        let start = index(startIndex, offsetBy: from)
        let end = index(start, offsetBy: to - from + 1)
        return String(self[start ..< end])
    }
}

let testString = "HelloWorld!"

print(testString.substring(from: 0, to: 4))     // 0 to 4 inclusive

Outputs Hello.

ThunderStruct
  • 1,504
  • 6
  • 23
  • 32
  • OP asked how to subscript the string with a range – Leo Dabus Jun 15 '19 at 22:44
  • Not really. OP asked for "something as simple as inputString[2...5]". Sure, it can be done by overloading the subscript operator, but this is a valid (arguably more readable) alternative solution. – ThunderStruct Jun 15 '19 at 23:20