0

I need INSTRREV to return the Int position of target within source after reverse (ie. backward) searching from start_pos to position of target.

I can't figure out how to get the position of target from target_char_range.

func INSTRREV( _ start_pos: Int, 
            _ source: String, 
            _ target: String ) -> Int
{
    let start_index = source.index( source.startIndex, offsetBy: 0 )
    let end_index = source.index( source.startIndex, offsetBy: start_pos - 1 )
    let source_range = start_index..<end_index

    let target_char_range = source.range(     of: target, 
                                                options: .backwards, 
                                                range: source_range ) 

        >>>>>>>>  HOW TO CONVERT target_char_range INTO Int ?   <<<<<<<<<<<

    let target_pos: Int = 0
    if target_pos > 0
    {
        return( target_pos )
    }
    else 
    {
        return( 0 )        // not found
    }
}
Doug Null
  • 7,989
  • 15
  • 69
  • 148
  • https://stackoverflow.com/questions/34540185/how-to-convert-index-to-type-int-in-swift ? – Larme Jan 24 '22 at 18:25

1 Answers1

0

First, I suggest changing your return type to Int? rather than overloading 0, which is a legitimate string position. Then you have to decide what the return value means. Is it the distance from the start or end of the string and is it the distance to the start or end of the substring?

Here's one implementation but changing either the bound or the distance measurement would be valid, depending on the return value's definition:

func INSTRREV( _ start_pos: Int,
            _ source: String,
            _ target: String ) -> Int?
{
    let end_index = source.index( source.startIndex, offsetBy: start_pos - 1 )
    let source_range = source.startIndex..<end_index
    let target_char_range = source.range(     of: target,
                                                options: .backwards,
                                                range: source_range )
    let target_pos = target_char_range?.upperBound
    if let target_pos = target_pos {
        return source.distance(from: target_pos, to: source.endIndex)
    } else {
        return nil
    }
}
Phillip Mills
  • 30,888
  • 4
  • 42
  • 57