Menu
Coddy logo textTech

Index Function

Lesson 15 of 19 in Coddy's Functions and Pointers in Golang course.

The strings package also contains a function called Index, which returns the index of a given character in a string.

An example of how this function works:

str := "Hello, World!"
char := "o"
index := strings.Index(str, char)
fmt.Println("Index of 'o' is", index)

The function takes the string and the character (str, char). If the char exists, the function returns the index; if it doesn't exist, it returns -1.

As always, indexing starts from 0. So, in this example, the result will be:

Index of o is 4
challenge icon

Challenge

Easy

Let's build our Index function! 😁

 

Write a function called index that takes two strings and returns an integer.

The first parameter will be the string.

The second parameter will be the character that we will check.

Check if the character exists; return the index if it does, return -1 if it doesn't.

 

Example:


Input:

"Coddy"
"y"

Output:

4

Try it yourself

// Your Code Here

All lessons in Functions and Pointers in Golang