Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Find the index of the last instance of a substring in Go (Golang)

Posted on March 16, 2020March 16, 2020 by admin

Table of Contents

  • Overview
  • Code:

Overview

In GO string are UTF-8 encoded. strings package of GO provides a LastIndex method that can be used to get the index of the last occurrence of a substring in a particular string. It returns -1 is the substring is not present in the given string.

Below is the signature of the function

func LastIndex(s, substr string) int

Let’s look at the working code

Code:

package main

import (
    "fmt"
    "strings"
)

func main() {
    //Output will be 1 as "bc" is present in "abcdef" at index 1
    res := strings.LastIndex("abcdef", "bc")
    fmt.Println(res)

    //Output will be 8 as "cd" is present in "abcdefabcdef" at index 8
    res = strings.LastIndex("abcdefabcdef", "cd")
    fmt.Println(res)

    //Output will be -1 as "ba" is not present in "abcdef"
    res = strings.LastIndex("abcdef", "ba")
    fmt.Println(res)
}

Output:

1
8
-1
Follow @golangbyexample

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme