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 check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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

#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 #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS? #Jan 8 How to Install Xcode Command Line Tools on MacOS?
You might also like these
Introduction to Angular modules Part 1: NgModule metadataAngularAdvanced nesting in Sass (SCSS) using at-rootSCSSJavaScript: how to detect a browser using the user agent?JavaScriptHow to obfuscate JavaScript code to hide it from View Source?JavaScriptFew more :nth-child examples in CSSCSSLearn to create profile card using HTML and CSSCSSVariables and Distance Functions in SCSS (Sass)SCSSHow to make flexbox items of the same size?CSSHow to modify the latest post array using get_posts() in WordPress?WordPressWhat are Class Constants in PHP?PHPABS and NEG functions in Envision BasicEnvision BasicHow to detect the Blog Page in WordPress?WordPress