Golang String - Get Index of Substring

[Pages:3]Golang String ? Get Index of Substring

Golang ? Get Index of Substring in String

To get the index of a substring in a string, Golang provides index functions. The syntax to get the index of the first occurrence of substring in a string is:

strings.Index(str, substring)

where

1. strings is the package 2. Index is the keyword 3. str is the string in which we have to find the index of substring .

strings.Index() function returns index that represents the position of first occurrence. Also, the function is case sensitive.

In this tutorial, we will learn how to find the position or index of a substring in a string.

Example 1 ? Get Index of Substring in a String

In this example, we will take a string Welcome to Golang Tutorial, Golang Examples and find the index of first occurrence of substring Golang .

example.go

package main import (

"fmt" "strings" "strconv" ) func main() { var str = "Welcome to Golang Tutorial, Golang Examples" var index = strings.Index(str, "Golang") fmt.Printf(strconv.Itoa(index)) }

Output

C:\workspace\go>go run example.go 11

Example 2 ? Index of Substring in String ? Substring not Present

If the substring is not present in the input string, strings.Index() returns -1 .

In the following example, we will take a string and substring such that substring is not present in the string. We will then use Index() to find the index of substring in string. Since substring is not present in the string, Index() should return -1.

example.go

package main import (

"fmt" "strings" "strconv" ) func main() { var str = "Welcome to Golang Tutorial, Golang Examples" var index = strings.Index(str, "Python") fmt.Printf(strconv.Itoa(index)) }

Output

C:\workspace\go>go run example.go -1

Conclusion

In this Golang Tutorial, we learned how to the index of a substring in given String.

Golang Golang Tutorial Run Golang Program Golang If Else

Golang Switch Golang For Loop Golang Comments Golang Functions Golang Array Golang Slice Golang Struct Golang Class Golang Range Golang Map Golang Goroutine Golang Channel

Golang String Operations Golang String Length Golang String Concatenation Golang Split String Golang String - Get Index of Substr Golang String to Uppercase Golang String to Lowercase Golang Convert String to Integer

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download