How to get start index and end index (as int) of substring in Swift?
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)



Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS Mar 2 WordPress: How to access first and random row values from a repeater field in ACF? Mar 1 The basics of CSS Box model Feb 27 WordPress: How to display slider repeater fields in ACF? Feb 26 Simple Page Hit Counter in PHP

You might also like these

A complete diagram with building blocks of an Angular applicationAngularCurrencyPipe in Angular 9 with ExamplesAngularObject destructuring in JavaScript: Unpacking fields from objects passed as function parameterJavaScriptWhat is Host Hardening and What are some Important Hardening Steps?Misctransform-origin Property in CSSCSSHow to create a smooth scrolling effect with CSS?CSSRIGHT JOIN in PostgresPostgresUNION and UNION ALL in PostgresPostgresAngular: Templates, directives, data binding, Services and dependency injectionAngularURL paths in DrupalDrupalSorting Arrays in JavaScriptJavaScriptThe actual difference between indexOf() and search() in JavaScriptJavaScript