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??

3
  • How about let input = "abcdefghij"; let cde = String(input.prefix(5).dropFirst(2))? Commented Jun 15, 2019 at 22:08
  • That's just what I was looking for, thanks man! Commented Jun 15, 2019 at 22:39
  • @Kali stackoverflow.com/questions/24092884/… Commented Jun 15, 2019 at 22:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

OP asked how to subscript the string with a range
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.