swift 3 problem with substring

Hello everyone, I have a problem when doing substring. I need to get a string "0x" and the next two characters. If the string is "SDdfsReY0x33Erdfg" I need to get "0x33".


I guess it's very simple but I'm new to swift programming and I can not understand how the ranges work. Excuse the syntactic and spelling errors.

Accepted Reply

It's not super simple to work with Swift Strings.


You may need to:

  1. Find and caculate the right indexes of the starting position and ending position of the substring you want to retrieve.
  2. Make them a `Range<String.Index>`.
  3. Retrieve the substring using the range.


let theString = "SDdfsReY0x33Erdfg"
if let rangeOfPrefix = theString.range(of: "0x") {
    //`rangeOfPrefix.lowerBound` points '0' of "0x".
    //`rangeOfPrefix.upperBound` points '3' next to "0x".
    //In Swift 3, only the original String can calculate the indices to itself.
    //(Assuming `offsetBy: 2` does not exceed the end of the String.)
    let twoCharactersNext = theString.index(rangeOfPrefix.upperBound, offsetBy: 2)
    let range = rangeOfPrefix.upperBound..<twoCharactersNext
    let result = theString[range]
    print(result) //-> 33
} else {
    print("'0x' not found")
}

Replies

You can write in Swift 3:


let output = "SDdfsReY0x33Erdfg"

let startingSequence = "0x"

startRange = output.range(of: startingSequence)

let char1 = output.character(at: startRange.location+2) // after 0x : get 51 (character 51)

let char2 = output.character(at: startRange.location+3) // after 0xn : get 51 (character 51)


then rebuild your 0x33

let s = String(UnicodeScalar(char1)!) + String(UnicodeScalar(char2)!)


It's not very clean, but that works on playground

It's not super simple to work with Swift Strings.


You may need to:

  1. Find and caculate the right indexes of the starting position and ending position of the substring you want to retrieve.
  2. Make them a `Range<String.Index>`.
  3. Retrieve the substring using the range.


let theString = "SDdfsReY0x33Erdfg"
if let rangeOfPrefix = theString.range(of: "0x") {
    //`rangeOfPrefix.lowerBound` points '0' of "0x".
    //`rangeOfPrefix.upperBound` points '3' next to "0x".
    //In Swift 3, only the original String can calculate the indices to itself.
    //(Assuming `offsetBy: 2` does not exceed the end of the String.)
    let twoCharactersNext = theString.index(rangeOfPrefix.upperBound, offsetBy: 2)
    let range = rangeOfPrefix.upperBound..<twoCharactersNext
    let result = theString[range]
    print(result) //-> 33
} else {
    print("'0x' not found")
}

Thank you all!