YogeshChauhan . com

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
amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

CurrencyPipe in Angular 9 with ExamplesAngularSocial Media Colors: Sass VariablesMiscWhat is iFrame in HTML? Why do we need it?HTMLHere’s what we can do with PHP date() functionPHPHow to create a sticky menu pin using CSS?CSSDefault Values in SCSS (Sass)SCSSGive buttons accessible namesUI/UXHow to get Current Year, Month and Date in JavaScript?JavaScriptMicroservices vs Monolithic ArchitectureMiscHow to show and hide an element on click in React?ReactIntroduction to components and templates Part 3: Data bindingAngularSpecificity of attribute selectorsCSS