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 How to add Read More Read Less Button using JavaScript? #2 How to check if radio button is checked or not using JavaScript? #3 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #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
How to avoid element shift on border change while hovering in CSS?CSSrandom function in SCSS (Sass)SCSSHow to add a ribbon on top of a container using CSS?CSSHow to Commit and Rollback Changes in SQL?SQL/MySQLHow to Create a Copy of a Table in SQL and MySQL?SQL/MySQLAvoid using new Array() in JavaScriptJavaScriptHow to remove N/A from Radio Button list in Drupal?DrupalIntroduction to components and templates Part 2: Templates and viewsAngularHow to control file extensions with an .htaccess file?MiscellaneousHow to use a Subquery to Insert Multiple Rows in SQL Table?SQL/MySQLWhat’s the difference between variables in CSS and SCSS (Sass)?CSSHow to display and animate image on scroll using JavaScript?JavaScript