Yogesh Chauhan's Blog

How to get start index and end index (as int) of substring in Swift?

in Swift on March 4, 2020

We can use distance(from:to:) method to get the start index and end index in Swift.

distance(from:to:) -> Returns the distance between two indices.

Declaration


func distance(from start: String.Index, to end: String.Index) -> String.IndexDistance

Example:


import Foundation

let sentence = "This article is written by Yogesh Chauhan"
if let range = sentence.range(of: "Yogesh") {
    let startIndex = sentence.distance(from: sentence.startIndex, to: range.lowerBound)
    let endIndex = sentence.distance(from: sentence.startIndex, to: range.upperBound)
    print(startIndex)
    print(endIndex)
}

//output

27
33

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
5 Steps to Create a Line using Canvas Tag in HTML5HTMLWhat is a component helper function in React?ReactHow to load variables, functions, and mixins from another module in SCSS?SCSSHow to use [] (square brackets) function in Envision Basic?Envision BasicHow to hide a DIV on clicks outside of it using jQuery?jQuerySome SQL LIKE Operators We Need to Keep in MindSQL/MySQLHow to use HTML picture Tag?HTMLPostgreSQL transactions using the BEGIN, COMMIT, and ROLLBACK statements.PostgresWhat is ECMAScript?JavaScript@use rule in SCSS (Sass)SCSSWhat’s a Log File and What are Log File Monitors?MiscellaneousHow to use $INSERT command in Envision Basic?Envision Basic