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.


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


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)



Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Gap in Flex?CSS3 JavaScript methods to use when you want to go back and forth in historyJavaScriptHow to Use password_hash and password_verify to Secure Your User’s Data (Especially Passwords)?PHPRBV Framework and closing of big brandsMiscellaneousHow to redirect or load a new document using JavaScript?JavaScriptCurrencyPipe in Angular 9 with ExamplesAngularHow to change perception and behavior of a person for acceptance of new systems?Miscellaneous10 Usability Blunders to AvoidUI/UXHow to define variables in SCSS (Sass)?SCSSJavaScript arrays: a separate data type or Objects?JavaScriptRevisiting variable scope in JavaScriptJavaScriptHow to Remove PHP File Extensions From Your Website URLs?PHP