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 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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
WordPress: How to find all posts from a custom post type with specific custom field?WordPressHow to Make CSS Lists Bullets Smaller?CSSThe substr() method in JavaScript and how it’s different from substring()JavaScriptAlternate Style Sheets in CSSCSSDifference between :where and :is in CSSCSSThe order Property in Flex Items in CSSCSSHow to Use SQL MAX() Function with Dates?SQL/MySQLHow to enable GD library support for PHP on windows server?PHPHow to get Current Hour, Minute and Second in JavaScript?JavaScriptHow to create a Star Ratings using CSS?CSSSimple Page Hit Counter in PHPPHPColumn and Table Alias in PostgresPostgres